$(function() {
    $('.foldable').click(function() {
       $(this).toggleClass('folded').next().toggle();
       $(this).next().find('.qommon-map').trigger('qommon:invalidate');
    });
    $('.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');
        });
    });

    /* hints on the computed expression widget */
    var validation_timeout_id = 0;
    $('input[data-validation-url]').on('change focus keyup', 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;
    });

    /* keep title/slug in sync */
    $('body').delegate('input[data-slug-sync]', 'keyup 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]');
            console.log(readonly_fields);
      if (readonly_fields.length) {
              console.log('a');
        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());
    });

    /* possibility to toggle the sidebar */
    if ($('#sidebar').length) {
      $('#main-content').after($('<span id="sidebar-toggle">&#8286;</span>'));
      $('#sidebar-toggle').click(function() {
        if ($('#sidebar').css('display') === 'none') {
          $('#main-content').animate({width: '75%'}, 400,
              function() {$('#sidebar').show()});
        } else {
          $('#sidebar').hide();
          $('#main-content').animate({width: '99%'});
        }
      });
    }

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