$(function() {
    $('.section.foldable > h2').click(function() {
       $(this).parent().find('.qommon-map').trigger('qommon:invalidate');
    });
    $('h4.foldable').click(function() {
       $(this).toggleClass('folded').next().toggle();
    });
    $('h4.foldable.folded').next().hide();

    /* insert variable code in textarea when clicking on them */
    $('#substvars td:nth-child(2)').css('cursor', 'pointer').click(function() {
       var current_val = $('textarea').val();
       position = $('textarea').get(0).selectionStart;
       if (position >= 0) {
         var code = $(this).text();
         var new_val = current_val.substr(0, position) + code + current_val.substr(position);
         $('textarea').val(new_val);
       }
       return true;
    });

    /* open theme preview in a iframe */
    $('a.theme-preview').click(function() {
        var html = '<div id="theme-preview"><iframe src="' + $(this).attr('href') + '"></iframe></div>';
        var title = $(this).parent().parent().find('label').text()
        var dialog = $(html).dialog({modal: true, title: title,
                width: $(window).width() - 180,
                height: $(window).height() - 80
        });
        return false;
    });

    /* highlight info text on hover */
    $('.action-info-text[data-button-name]').each(function(idx, elem) {
        $('[name=' + $(elem).data('button-name') + ']').on('mouseenter', function() {
           $(elem).addClass('highlight');
        }).on('mouseleave', function() {
           $(elem).removeClass('highlight');
        });
    });

    /* close advanced section */
    $('fieldset.form-plus').addClass('closed');
    /* handle toggling advanced section */
    $('fieldset.form-plus legend').on('click', function() {
      $(this).parent().toggleClass('closed');
    });
    /* open advanced section if there's a field with errors */
    $('fieldset.form-plus').each(function(idx, elem) {
      if ($(elem).find('div.error').length) {
        $(elem).removeClass('closed');
      }
    });

    /* hints on the computed expression widget */
    var validation_timeout_id = 0;
    $('input[data-validation-url]').on('change focus input', function() {
      var val = $(this).val();
      var $widget = $(this).parents('.ComputedExpressionWidget');
      var validation_url = $(this).data('validation-url');
      clearTimeout(validation_timeout_id);
      validation_timeout_id = setTimeout(function() {
        $.ajax({
          url: validation_url,
          data: {expression: val},
          dataType: 'json',
          success: function(data) {
            $widget.removeClass('hint-warning');
            $widget.removeClass('hint-error');
            if (data.klass) {
              $widget.addClass('hint-' + data.klass);
            }
            $widget.prop('title', data.msg);
          }
        })}, 250);
      return false;
    });

    $('div[data-validation-url]').each(function(idx, elem) {
      var $widget = $(this);
      var widget_name = $widget.find('select').attr('name');
      var prefix = widget_name.replace(/\$[a-z]*/, '') + '$';
      $(this).find('input, select').on('change focus input', function() {
        clearTimeout($widget.validation_timeout_id);
        $widget.validation_timeout_id = setTimeout(function() {
          var data = Object();
          $widget.find('select, input').each(function(idx, elem) {
            data[$(elem).attr('name').replace(prefix, '')] = $(elem).val();
          });
          $.ajax({
            url: $widget.data('validation-url'),
            data: data,
            dataType: 'json',
            success: function(data) {
              $widget.removeClass('hint-warning');
              $widget.removeClass('hint-error');
              if (data.klass) {
                $widget.addClass('hint-' + data.klass);
              }
              $widget.prop('title', data.msg);
            }
          })}, 250);
        return false;
      });
    });

    /* keep title/slug in sync */
    $('body').delegate('input[data-slug-sync]', 'input change paste',
        function() {
            var $slug_field = $(this).parents('form').find('[name=' + $(this).data('slug-sync') + ']');
            if ($slug_field.prop('readonly')) return;
            $slug_field.val($.slugify($(this).val()));
    });

    /* remove readonly attribute from fields */
    $('body').delegate('a.change-nevertheless', 'click', function(e) {
      var readonly_fields = $(this).parents('form').find('input[readonly]');
      if (readonly_fields.length) {
        readonly_fields.prop('readonly', false);
        readonly_fields[0].focus();
      }
      $(this).parent().hide();
      return false;
    });

    /* submission channel */
    $('div.submit-channel-selection').show().find('select').on('change', function() {
      $('input[type=hidden][name=submission_channel]').val($(this).val());
    });

    /* new action form */
    $('#new-action-form select').on('change', function() {
      if ($(this).val() == '') {
        $('#new-action-form select').prop('disabled', null)
      } else {
        $('#new-action-form select').prop('disabled', 'disabled')
        $(this).prop('disabled', null)
      }
      return false;
    });

    /* possibility to toggle the sidebar */
    if ($('#sidebar').length) {
      $('#sidebar-toggle').click(function() {
        if ($('#sticky-sidebar').css('display') === 'none') {
          $('#sidebar').animate(
              {'max-width': '23rem'},
              400,
              function() {
                $('#sticky-sidebar').show()
                $(window).trigger('wcs:sidebar-toggled');
              }
          );
        } else {
          $('#sticky-sidebar').hide();
          $('#sidebar').animate(
              {'max-width': '0rem'},
              400,
              function() {
                $(window).trigger('wcs:sidebar-toggled');
              }
          );
        }
      });
    }

    /* load html parts asynchronously */
    $('[data-async-url]').each(function(idx, elem) {
      $(elem).load($(elem).data('async-url'));
    });

    /* keep sidebar sticky */
    if ($('#sticky-sidebar').length) {
      var $window = $(window);
      var sidebar_fixed_from = $('#sticky-sidebar').offset().top;
      var sidebar_top = $('#sticky-sidebar').position().top;
      $window.bind('scroll', function() {
        var pos = $window.scrollTop();
        var minus = 0;
        if (pos >= sidebar_fixed_from) {
          $('#sticky-sidebar').css('top', pos - (sidebar_fixed_from - sidebar_top));
        } else {
          $('#sticky-sidebar').css('top', 'auto');
          minus = sidebar_fixed_from - pos;
        }
        $('#sticky-sidebar').css('height', 'calc(100vh - 5px - ' + minus + 'px)');
      });
      $window.trigger('scroll');
    }

    $('#inspect-test-tools form').on('submit', function() {
      var data = $(this).serialize();
      $.ajax({url: 'inspect-tool',
          xhrFields: { withCredentials: true },
          data: $(this).serialize(),
          method: 'POST',
          async: true,
          dataType: 'html',
          success: function(data) {
            $('#test-tool-result').empty().append($(data));
          }
      });
      return false;
    });
    $('#inspect-test-tools textarea').on('keydown', function(e) {
      if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
        $(this).parents('form').trigger('submit');
        return false;
      }
      return true;
    });

    if ($('svg').length && typeof(svgPanZoom) === 'function') {
        var panned_svg = svgPanZoom('svg', {controlIconsEnabled: true});
        $(window).on('resize wcs:sidebar-toggled gadjo:sidepage-toggled', function() {
            panned_svg.resize();
        });
    }
});
