$(function() {

  function prepare_dynamic_widgets()
  {
    $('[data-dynamic-display-parent]').off('change input').on('change input', function() {
      var sel1 = '[data-dynamic-display-child-of="' + $(this).attr('name') + '"]';
      var sel2 = '[data-dynamic-display-value="' + $(this).val() + '"]';
      var sel3 = '[data-dynamic-display-invert-value][data-dynamic-display-invert-value!="' + $(this).val() + '"]';
      var sel4 = '[data-dynamic-display-value-in*="' + $(this).val() + '"]';
      $(sel1).hide();
      $(sel1 + sel2).show();
      $(sel1 + sel3).show();
      $(sel1 + sel4).show();
    });
    $('[data-dynamic-display-child-of]').hide();
    $('select[data-dynamic-display-parent]').trigger('change');
    $('[data-dynamic-display-parent]:checked').trigger('change');
  }

  function prepate_select_or_other_widgets() {
    $('.SingleSelectWidgetWithOther').each(function(idx, elem) {
      var $widget = $(elem);
      $widget.find('select').off('change input').on('change input', function() {
        var val = $(this).val();
        if (val == '__other') {
          $widget.find('.StringWidget').show();
        } else {
          $widget.find('.StringWidget').hide();
        }
      });
      $widget.find('select').trigger('change');
    });
  }

  function prepare_confirmation_buttons() {
    $('button[data-ask-for-confirmation]').off('click').on('click', function() {
      if (confirm(WCS_I18N.confirmation) != true) {
        return false;
      } else {
        return true;
      }
    });
  }

  $('[data-content-url]').each(function(idx, elem) {
    $.ajax({url: $(elem).data('content-url'),
            xhrFields: { withCredentials: true },
            async: true,
            dataType: 'jsonp',
            crossDomain: true,
            success: function(data) { $(elem).html(data.content); },
            error: function(error) { windows.console && console.log('bouh', error); }
           });
  });

  function prepare_widgets() {
    prepare_dynamic_widgets();
    prepate_select_or_other_widgets();
    prepare_confirmation_buttons();
  }

  prepare_widgets();
  $(document).on('wcs:dialog-loaded', prepare_widgets);
  $(document).on('wcs:new-widgets-on-page', prepare_widgets);
});
