script: slot
(function() {
  var ace_editor_content, addCaptcha, detectMobileBrowser, doubleSidebar, initCaptcha, navbox_results, navbox_select, navboxize, permissionsContent, pointerContent, reqIndex, sidebarToggle, singleSidebar, snakeCase, toggleShade, warn, wrapDeckoLayout, wrapSidebarToggle;

  window.wagn || (window.wagn = {});

  $.extend(wagn, {
    editorContentFunctionMap: {
      '.ace-editor-textarea': function() {
        return ace_editor_content(this[0]);
      },
      '.tinymce-textarea': function() {
        return tinyMCE.get(this[0].id).getContent();
      },
      '.pointer-select': function() {
        return pointerContent(this.val());
      },
      '.pointer-multiselect': function() {
        return pointerContent(this.val());
      },
      '.pointer-radio-list': function() {
        return pointerContent(this.find('input:checked').val());
      },
      '.pointer-list-ul': function() {
        return pointerContent(this.find('input').map(function() {
          return $(this).val();
        }));
      },
      '.pointer-checkbox-list': function() {
        return pointerContent(this.find('input:checked').map(function() {
          return $(this).val();
        }));
      },
      '.pointer-select-list': function() {
        return pointerContent(this.find('.pointer-select select').map(function() {
          return $(this).val();
        }));
      },
      '.pointer-mixed': function() {
        var element;
        element = '.pointer-checkbox-sublist input:checked,.pointer-sublist-ul input';
        return pointerContent(this.find(element).map(function() {
          return $(this).val();
        }));
      },
      '.perm-editor': function() {
        return permissionsContent(this);
      }
    },
    editorInitFunctionMap: {
      '.date-editor': function() {
        return this.datepicker({
          dateFormat: 'yy-mm-dd'
        });
      },
      'textarea': function() {
        return $(this).autosize();
      },
      '.ace-editor-textarea': function() {
        return wagn.initAce($(this));
      },
      '.tinymce-textarea': function() {
        return wagn.initTinyMCE(this[0].id);
      },
      '.pointer-list-editor': function() {
        this.sortable({
          handle: '.handle',
          cancel: ''
        });
        return wagn.initPointerList(this.find('input'));
      },
      '.file-upload': function() {
        return wagn.upload_file(this);
      },
      '.etherpad-textarea': function() {
        return $(this).closest('form').find('.edit-submit-button').attr('class', 'etherpad-submit-button');
      }
    },
    upload_file: function(fileupload) {
      var $_fileupload, url;
      $(fileupload).bind('fileuploadsubmit', function(e, data) {
        var $_this, card_name, type_id;
        $_this = $(this);
        card_name = $_this.siblings(".attachment_card_name:first").attr("name");
        type_id = $_this.siblings("#attachment_type_id").val();
        return data.formData = {
          "card[type_id]": type_id,
          "attachment_upload": card_name
        };
      });
      $_fileupload = $(fileupload);
      if ($_fileupload.closest("form").attr("action").indexOf("update") > -1) {
        url = "/card/update/" + $(fileupload).siblings("#file_card_name").val();
      } else {
        url = "/card/create";
      }
      return $(fileupload).fileupload({
        url: url,
        dataType: 'html',
        done: wagn.doneFile,
        add: wagn.chooseFile,
        progressall: wagn.progressallFile
      });
    },
    initPointerList: function(input) {
      var optionsCard;
      optionsCard = input.closest('ul').data('options-card');
      return input.autocomplete({
        source: wagn.prepUrl(wagn.rootPath + '/' + optionsCard + '.json?view=name_complete')
      });
    },
    setTinyMCEConfig: function(string) {
      var setter;
      setter = function() {
        var error;
        try {
          return $.parseJSON(string);
        } catch (error) {
          return {};
        }
      };
      return wagn.tinyMCEConfig = setter();
    },
    initAce: function(textarea) {
      var editDiv, editor, hash, mode, type_code;
      type_code = textarea.attr("data-card-type-code");
      hash = {};
      hash["java_script"] = "javascript";
      hash["coffee_script"] = "coffee";
      hash["css"] = "css";
      hash["scss"] = "scss";
      hash["html"] = "html";
      hash["search_type"] = "json";
      hash["layout_type"] = "html";
      mode = hash[type_code];
      if (!mode) {
        textarea.autosize();
        return;
      }
      editDiv = $("<div>", {
        position: "absolute",
        width: "auto",
        height: textarea.height()
      }).insertBefore(textarea);
      textarea.css("visibility", "hidden");
      textarea.css("height", "0px");
      ace.config.set('basePath', '/assets/ace');
      editor = ace.edit(editDiv[0]);
      editor.renderer.setShowGutter(true);
      editor.getSession().setValue(textarea.val());
      editor.setTheme("ace/theme/github");
      editor.getSession().setMode("ace/mode/" + mode);
      editor.setOption("showPrintMargin", false);
      editor.getSession().setTabSize(2);
      editor.getSession().setUseSoftTabs(true);
      editor.setOptions({
        maxLines: 30
      });
    },
    initTinyMCE: function(el_id) {
      var conf, hard_conf, user_conf;
      conf = {
        plugins: 'autoresize',
        autoresize_max_height: 500
      };
      user_conf = wagn.tinyMCEConfig != null ? wagn.tinyMCEConfig : {};
      hard_conf = {
        mode: 'exact',
        elements: el_id,
        content_css: wagn.cssPath,
        entity_encoding: 'raw'
      };
      $.extend(conf, user_conf, hard_conf);
      return tinyMCE.init(conf);
    },
    chooseFile: function(e, data) {
      var editor;
      data.form.find('button[type=submit]').attr('disabled', true);
      editor = $(this).closest('.card-editor');
      $('#progress').show();
      editor.append('<input type="hidden" class="extra_upload_param" value="true" name="attachment_upload">');
      editor.append('<input type="hidden" class="extra_upload_param" value="preview_editor" name="view">');
      data.submit();
      editor.find('.choose-file').hide();
      return editor.find('.extra_upload_param').remove();
    },
    progressallFile: function(e, data) {
      var progress;
      progress = parseInt(data.loaded / data.total * 100, 10);
      return $('#progress .progress-bar').css('width', progress + '%');
    },
    doneFile: function(e, data) {
      var editor;
      editor = $(this).closest('.card-editor');
      editor.find('.chosen-file').replaceWith(data.result);
      return data.form.find('button[type=submit]').attr('disabled', false);
    },
    isTouchDevice: function() {
      if ('ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch) {
        return true;
      } else {
        return detectMobileBrowser();
      }
    }
  }, detectMobileBrowser = function(userAgent) {
    userAgent = navigator.userAgent || navigator.vendor || window.opera;
    return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0, 4));
  });

  wrapDeckoLayout = function() {
    var $footer;
    $footer = $('body > footer').first();
    $('body > article, body > aside').wrapAll('<div class="container"/>');
    $('div.container > article, div.container > aside').wrapAll('<div class="row row-offcanvas">');
    if ($footer) {
      return $('body').append($footer);
    }
  };

  wrapSidebarToggle = function(toggle) {
    return "<div class='container'><div class='row'>" + toggle + "</div></div>";
  };

  sidebarToggle = function(side) {
    return "<button class='offcanvas-toggle offcanvas-toggle-" + side + " btn btn-secondary visible-xs' data-toggle='offcanvas-" + side + "'><span class='glyphicon glyphicon-chevron-" + (side === 'left' ? 'right' : 'left') + "'/></button>";
  };

  singleSidebar = function(side) {
    var $article, $aside;
    $article = $('body > article').first();
    $aside = $('body > aside').first();
    $article.addClass("col-xs-12 col-sm-9");
    $aside.addClass("col-xs-6 col-sm-3 sidebar-offcanvas sidebar-offcanvas-" + side);
    if (side === 'left') {
      $('body').append($aside).append($article);
    } else {
      $('body').append($article).append($aside);
    }
    wrapDeckoLayout();
    return $article.prepend(wrapSidebarToggle(sidebarToggle(side)));
  };

  doubleSidebar = function() {
    var $article, $asideLeft, $asideRight;
    $article = $('body > article').first();
    $asideLeft = $('body > aside').first();
    $asideRight = $($('body > aside')[1]);
    $article.addClass("col-xs-12 col-sm-6");
    $asideLeft.addClass("col-xs-6 col-sm-3 sidebar-offcanvas sidebar-offcanvas-left");
    $asideRight.addClass("col-xs-6 col-sm-3 sidebar-offcanvas sidebar-offcanvas-right");
    $('body').append($asideLeft).append($article).append($asideRight);
    wrapDeckoLayout();
    return $article.prepend(wrapSidebarToggle("" + (sidebarToggle('right')) + (sidebarToggle('left'))));
  };

  $(window).ready(function() {
    var firstShade;
    switch (false) {
      case !$('body').hasClass('right-sidebar'):
        singleSidebar('right');
        break;
      case !$('body').hasClass('left-sidebar'):
        singleSidebar('left');
        break;
      case !$('body').hasClass('two-sidebar'):
        doubleSidebar();
    }
    $('[data-toggle="offcanvas-left"]').click(function() {
      $('.row-offcanvas').removeClass('right-active').toggleClass('left-active');
      return $(this).find('span.glyphicon').toggleClass('glyphicon-chevron-left glyphicon-chevron-right');
    });
    $('[data-toggle="offcanvas-right"]').click(function() {
      $('.row-offcanvas').removeClass('left-active').toggleClass('right-active');
      return $(this).find('span.glyphicon').toggleClass('glyphicon-chevron-left glyphicon-chevron-right');
    });
    $('body').on('click', '.cancel-upload', function() {
      var editor;
      editor = $(this).closest('.card-editor');
      editor.find('.choose-file').show();
      editor.find('.chosen-file').empty();
      editor.find('.progress').show();
      editor.find('#progress .progress-bar').css('width', '0%');
      return editor.find('#progress').hide();
    });
    $('.navbox').autocomplete({
      html: 'html',
      source: navbox_results,
      select: navbox_select
    });
    $('body').on('click', '.pointer-item-add', function(event) {
      var input, last_item, new_item;
      last_item = $(this).closest('.content-editor').find('.pointer-li:last');
      new_item = last_item.clone();
      input = new_item.find('input');
      input.val('');
      last_item.after(new_item);
      wagn.initPointerList(input);
      return event.preventDefault();
    });
    $('body').on('click', '.pointer-item-delete', function() {
      var item;
      item = $(this).closest('li');
      if (item.closest('ul').find('.pointer-li').length > 1) {
        return item.remove();
      } else {
        return item.find('input').val('');
      }
    });
    $('body').on('show.bs.tab', 'a.load[data-toggle=tab][data-url]', function(e) {
      var tab_id, url;
      tab_id = $(e.target).attr('href');
      url = $(e.target).data('url');
      $(e.target).removeClass('load');
      return $(tab_id).load(url);
    });
    $('body').on('click', '.toolbar-pin.active', function(e) {
      e.preventDefault();
      $(this).blur();
      $('.toolbar-pin').removeClass('active').addClass('inactive');
      return $.ajax('/*toolbar_pinned', {
        type: 'PUT',
        data: 'card[content]=false'
      });
    });
    $('body').on('click', '.toolbar-pin.inactive', function(e) {
      e.preventDefault();
      $(this).blur();
      $('.toolbar-pin').removeClass('inactive').addClass('active');
      return $.ajax('/*toolbar_pinned', {
        type: 'PUT',
        data: 'card[content]=true'
      });
    });
    $('body').on('click', '.btn-item-delete', function() {
      return $(this).find('.glyphicon').addClass("glyphicon-hourglass").removeClass("glyphicon-remove");
    });
    $('body').on('click', '.btn-item-add', function() {
      return $(this).find('.glyphicon').addClass("glyphicon-hourglass").removeClass("glyphicon-plus");
    });
    $('body').on('mouseenter', '.btn-item-delete', function() {
      $(this).find('.glyphicon').addClass("glyphicon-remove").removeClass("glyphicon-ok");
      return $(this).addClass("btn-danger").removeClass("btn-primary");
    });
    $('body').on('mouseleave', '.btn-item-delete', function() {
      $(this).find('.glyphicon').addClass("glyphicon-ok").removeClass("glyphicon-remove");
      return $(this).addClass("btn-primary").removeClass("btn-danger");
    });
    $('body').on('hidden.bs.modal', function(event) {
      var menu_slot, modal_content, params, slot, url;
      modal_content = $(event.target).find('.modal-dialog > .modal-content');
      if ($(event.target).attr('id') !== 'modal-main-slot') {
        slot = $(event.target).slot();
        menu_slot = slot.find('.menu-slot:first');
        url = wagn.rootPath + '/~' + slot.data('card-id');
        params = {
          view: 'menu'
        };
        if (slot.isMain()) {
          params['is_main'] = true;
        }
        modal_content.empty();
        return $.ajax(url, {
          type: 'GET',
          data: params,
          success: function(data) {
            return menu_slot.replaceWith(data);
          }
        });
      }
    });
    $('body').on('click', '.perm-vals input', function() {
      return $(this).slot().find('#inherit').attr('checked', false);
    });
    $('body').on('click', '.perm-editor #inherit', function() {
      var slot;
      slot = $(this).slot();
      slot.find('.perm-group input:checked').attr('checked', false);
      return slot.find('.perm-indiv input').val('');
    });
    $('body').on('click', '.rule-submit-button', function() {
      var checked, f;
      f = $(this).closest('form');
      checked = f.find('.set-editor input:checked');
      if (checked.val()) {
        if (checked.attr('warning')) {
          return confirm(checked.attr('warning'));
        } else {
          return true;
        }
      } else {
        f.find('.set-editor').addClass('attention');
        $(this).notify('To what Set does this Rule apply?');
        return false;
      }
    });
    $('body').on('click', '.submit-modal', function() {
      return $(this).closest('.modal-content').find('form').submit();
    });
    $('body').on('click', '.shade-view h1', function() {
      var toggleThis;
      toggleThis = $(this).slot().find('.shade-content').is(':hidden');
      toggleShade($(this).closest('.pointer-list').find('.shade-content:visible').parent());
      if (toggleThis) {
        return toggleShade($(this).slot());
      }
    });
    if (firstShade = $('.shade-view h1')[0]) {
      $(firstShade).trigger('click');
    }
    $('body').on('change', '.go-to-selected select', function() {
      var val;
      val = $(this).val();
      if (val !== '') {
        return window.location = wagn.rootPath + escape(val);
      }
    });
    $('body').on('click', '.open-slow-items', function() {
      var panel;
      panel = $(this).closest('.panel-group');
      panel.find('.open-slow-items').removeClass('open-slow-items').addClass('close-slow-items');
      panel.find('.toggle-fast-items').text("show < 100ms");
      panel.find('.duration-ok').hide();
      return panel.find('.panel-danger > .panel-collapse').collapse('show').find('a > span').addClass('show-fast-items');
    });
    $('body').on('click', '.close-slow-items', function() {
      var panel;
      panel = $(this).closest('.panel-group');
      panel.find('.close-slow-items').removeClass('close-slow-items').addClass('open-slow-items');
      panel.find('.toggle-fast-items').text("hide < 100ms");
      panel.find('.panel-danger > .panel-collapse').collapse('hide').removeClass('show-fast-items');
      return panel.find('.duration-ok').show();
    });
    $('body').on('click', '.toggle-fast-items', function() {
      var panel;
      panel = $(this).closest('.panel-group');
      if ($(this).text() === 'hide < 100ms') {
        panel.find('.duration-ok').hide();
        return $(this).text("show < 100ms");
      } else {
        panel.find('.duration-ok').show();
        return $(this).text("hide < 100ms");
      }
    });
    return $('body').on('click', '.show-fast-items', function(event) {
      var panel;
      $(this).removeClass('show-fast-items');
      panel = $(this).closest('.panel-group');
      panel.find('.duration-ok').show();
      panel.find('.show-fast-items').removeClass('show-fast-items');
      panel.find('.panel-collapse').collapse('show');
      return event.stopPropagation();
    });
  });

  toggleShade = function(shadeSlot) {
    shadeSlot.find('.shade-content').slideToggle(1000);
    return shadeSlot.find('.glyphicon').toggleClass('glyphicon-triangle-right glpyphicon-triangle-bottom');
  };

  permissionsContent = function(ed) {
    var groups, indivs;
    if (ed.find('#inherit').is(':checked')) {
      return '_left';
    }
    groups = ed.find('.perm-group input:checked').map(function() {
      return $(this).val();
    });
    indivs = ed.find('.perm-indiv input').map(function() {
      return $(this).val();
    });
    return pointerContent($.makeArray(groups).concat($.makeArray(indivs)));
  };

  pointerContent = function(vals) {
    var list;
    list = $.map($.makeArray(vals), function(v) {
      if (v) {
        return '[[' + v + ']]';
      }
    });
    return $.makeArray(list).join("\n");
  };

  ace_editor_content = function(element) {
    var ace_div, editor;
    ace_div = $(element).siblings(".ace_editor");
    editor = ace.edit(ace_div[0]);
    return editor.getSession().getValue();
  };

  reqIndex = 0;

  navbox_results = function(request, response) {
    var f, formData;
    f = this.element.closest('form');
    formData = f.serialize() + '&view=complete';
    return this.xhr = $.ajax({
      url: wagn.prepUrl(wagn.rootPath + '/:search.json'),
      data: formData,
      dataType: "json",
      wagReq: ++reqIndex,
      success: function(data, status) {
        if (this.wagReq === reqIndex) {
          return response(navboxize(request.term, data));
        }
      },
      error: function() {
        if (this.wagReq === reqIndex) {
          return response([]);
        }
      }
    });
  };

  navboxize = function(term, results) {
    var items;
    items = [];
    $.each(['search', 'add', 'new'], function(index, key) {
      var i, val;
      if (val = results[key]) {
        i = {
          value: term,
          prefix: key,
          icon: 'plus',
          label: '<strong class="highlight">' + term + '</strong>'
        };
        if (key === 'search') {
          i.icon = key;
          i.term = term;
        } else if (key === 'add') {
          i.href = '/card/new?card[name]=' + encodeURIComponent(val);
        } else if (key === 'new') {
          i.type = 'add';
          i.href = '/new/' + val[1];
        }
        return items.push(i);
      }
    });
    $.each(results['goto'], function(index, val) {
      return items.push({
        icon: 'share-alt',
        prefix: 'go to',
        value: val[0],
        label: val[1],
        href: '/' + val[2]
      });
    });
    $.each(items, function(index, i) {
      return i.label = '<span class="glyphicon glyphicon-' + i.icon + '"></span><span class="navbox-item-label">' + i.prefix + ':</span> ' + '<span class="navbox-item-value">' + i.label + '</span>';
    });
    return items;
  };

  navbox_select = function(event, ui) {
    if (ui.item.term) {
      $(this).closest('form').submit();
    } else {
      window.location = wagn.rootPath + ui.item.href;
    }
    return $(this).attr('disabled', 'disabled');
  };

  $.extend(wagn, {
    initializeEditors: function(range, map) {
      if (map == null) {
        map = wagn.editorInitFunctionMap;
      }
      return $.each(map, function(selector, fn) {
        return $.each(range.find(selector), function() {
          return fn.call($(this));
        });
      });
    },
    prepUrl: function(url, slot) {
      var main, slotdata, xtra;
      xtra = {};
      main = $('#main').children('.card-slot').data('cardName');
      if (main != null) {
        xtra['main'] = main;
      }
      if (slot) {
        if (slot.isMain()) {
          xtra['is_main'] = true;
        }
        slotdata = slot.data('slot');
        if (slotdata != null) {
          wagn.slotParams(slotdata, xtra, 'slot');
        }
      }
      return url + ((url.match(/\?/) ? '&' : '?') + $.param(xtra));
    },
    slotParams: function(raw, processed, prefix) {
      return $.each(raw, function(key, value) {
        var cgiKey;
        cgiKey = prefix + '[' + snakeCase(key) + ']';
        if (key === 'items') {
          return wagn.slotParams(value, processed, cgiKey);
        } else {
          return processed[cgiKey] = value;
        }
      });
    },
    slotReady: function(func) {
      return $('document').ready(function() {
        return $('body').on('slotReady', '.card-slot', function(e) {
          e.stopPropagation();
          return func.call(this, $(this));
        });
      });
    },
    pingName: function(name, success) {
      return $.getJSON(wagn.rootPath + '/', {
        format: 'json',
        view: 'status',
        'card[name]': name
      }, success);
    }
  });

  jQuery.fn.extend({
    slot: function() {
      var parent_slot, target_slot;
      if (this.data('slot-selector')) {
        target_slot = this.closest(this.data('slot-selector'));
        parent_slot = this.closest('.card-slot');
        while (target_slot.length === 0 && parent_slot.length > 0) {
          target_slot = $(parent_slot).find(this.data('slot-selector'));
          parent_slot = $(parent_slot).parent().closest('.card-slot');
        }
        if (target_slot.length === 0) {
          return $(this.data('slot-selector'));
        } else {
          return target_slot;
        }
      } else {
        return this.closest('.card-slot');
      }
    },
    setSlotContent: function(val) {
      var s, v;
      s = this.slot();
      v = $(val);
      if (!v[0]) {
        v = val;
      }
      s.replaceWith(v);
      v.trigger('slotReady');
      return v;
    },
    slotSuccess: function(data) {
      var newslot, notice;
      if (data.redirect) {
        return window.location = data.redirect;
      } else {
        notice = this.attr('notify-success');
        newslot = this.setSlotContent(data);
        if (newslot.jquery) {
          wagn.initializeEditors(newslot);
          if (notice != null) {
            return newslot.notify(notice);
          }
        }
      }
    },
    slotError: function(status, result) {
      if (status === 403) {
        return this.setSlotContent(result);
      } else {
        this.notify(result);
        if (status === 409) {
          return this.slot().find('.current_revision_id').val(this.slot().find('.new-current-revision-id').text());
        } else if (status === 449) {
          return this.slot().find('g-recaptcha').reloadCaptcha();
        }
      }
    },
    notify: function(message) {
      var form, notice, slot;
      slot = this.slot();
      notice = slot.find('.card-notice');
      if (!notice[0]) {
        notice = $('<div class="card-notice"></div>');
        form = slot.find('.card-form');
        if (form[0]) {
          $(form[0]).append(notice);
        } else {
          slot.append(notice);
        }
      }
      notice.html(message);
      return notice.show('blind');
    },
    report: function(message) {
      var report;
      report = this.slot().find('.card-report');
      if (!report[0]) {
        return false;
      }
      report.hide();
      report.html(message);
      report.show('drop', 750);
      return setTimeout((function() {
        return report.hide('drop', 750);
      }), 3000);
    },
    isMain: function() {
      return this.slot().parent('#main')[0];
    },
    reloadCaptcha: function() {
      this[0].empty();
      return grecaptcha.render(this[0], {
        sitekey: wagn.recaptchaKey
      });
    },
    autosave: function() {
      var form_data, id, multi, reportee, slot, submit_url;
      slot = this.slot();
      if (this.attr('no-autosave')) {
        return;
      }
      multi = this.closest('.form-group');
      if (multi[0]) {
        if (!(id = multi.data('cardId'))) {
          return;
        }
        reportee = ': ' + multi.data('cardName');
      } else {
        id = slot.data('cardId');
        reportee = '';
      }
      submit_url = wagn.rootPath + '/update/~' + id;
      form_data = $('#edit_card_' + id).serializeArray().reduce((function(obj, item) {
        obj[item.name] = item.value;
        return obj;
      }), {
        'draft': 'true',
        'success[view]': 'blank'
      });
      return $.ajax(submit_url, {
        data: form_data,
        type: 'POST'
      });
    },
    setContentFieldsFromMap: function(map) {
      var this_form;
      if (map == null) {
        map = wagn.editorContentFunctionMap;
      }
      this_form = $(this);
      return $.each(map, function(selector, fn) {
        return this_form.setContentFields(selector, fn);
      });
    },
    setContentFields: function(selector, fn) {
      return $.each(this.find(selector), function() {
        return $(this).setContentField(fn);
      });
    },
    setContentField: function(fn) {
      var field, init_val, new_val;
      field = this.closest('.card-editor').find('.card-content');
      init_val = field.val();
      new_val = fn.call(this);
      field.val(new_val);
      if (init_val !== new_val) {
        return field.change();
      }
    }
  });

  setInterval((function() {
    return $('.card-form').setContentFieldsFromMap();
  }), 20000);

  $(window).ready(function() {
    $.ajaxSetup({
      cache: false
    });
    setTimeout((function() {
      return wagn.initializeEditors($('body'));
    }), 10);
    $('body').on('ajax:success', '.slotter', function(event, data, c, d) {
      var slot_top_pos;
      if (!event.slotSuccessful) {
        slot_top_pos = $(this).slot().offset().top;
        $(this).slotSuccess(data);
        if ($(this).hasClass("close-modal")) {
          $(this).closest('.modal').modal('hide');
        }
        if ($(this).hasClass("card-paging-link")) {
          $("body").scrollTop(slot_top_pos);
        }
        return event.slotSuccessful = true;
      }
    });
    $('body').on('loaded.bs.modal', null, function(event) {
      if (!event.slotSuccessful) {
        wagn.initializeEditors($(event.target));
        $(event.target).find(".card-slot").trigger("slotReady");
        return event.slotSuccessful = true;
      }
    });
    $('body').on('ajax:error', '.slotter', function(event, xhr) {
      return $(this).slotError(xhr.status, xhr.responseText);
    });
    $('body').on('click', 'button.slotter', function(event) {
      if (!$.rails.allowAction($(this))) {
        return false;
      }
      return $.rails.handleRemote($(this));
    });
    $('body').on('ajax:beforeSend', '.slotter', function(event, xhr, opt) {
      var args, data, iframeUploadFilter, input, widget;
      if (opt.skip_before_send) {
        return;
      }
      if (!opt.url.match(/home_view/)) {
        opt.url = wagn.prepUrl(opt.url, $(this).slot());
      }
      if ($(this).is('form')) {
        if (wagn.recaptchaKey && $(this).attr('recaptcha') === 'on' && !($(this).find('.g-recaptcha')[0])) {
          if ($('.g-recaptcha')[0]) {
            addCaptcha(this);
          } else {
            initCaptcha(this);
          }
          return false;
        }
        if (data = $(this).data('file-data')) {
          input = $(this).find('.file-upload');
          if (input[1]) {
            $(this).notify("Wagn does not yet support multiple files in a single form.");
            return false;
          }
          widget = input.data('blueimpFileupload');
          if (!widget._isXHRUpload(widget.options)) {
            $(this).find('[name=success]').val('_self');
            opt.url += '&simulate_xhr=true';
            iframeUploadFilter = function(data) {
              return data.find('body').html();
            };
            opt.dataFilter = iframeUploadFilter;
          }
          args = $.extend(opt, widget._getAJAXSettings(data), {
            url: opt.url
          });
          args.skip_before_send = true;
          $.ajax(args);
          return false;
        }
      }
    });
    $('body').on('submit', '.card-form', function() {
      $(this).setContentFieldsFromMap();
      $(this).find('.card-content').attr('no-autosave', 'true');
      return true;
    });
    $('body').on('click', '.submitter', function() {
      return $(this).closest('form').submit();
    });
    $('body').on('click', '.renamer-updater', function() {
      return $(this).closest('form').find('#card_update_referers').val('true');
    });
    $('body').on('submit', '.edit_name-view .card-form', function() {
      var confirmer;
      confirmer = $(this).find('.alert');
      if (confirmer.is(':hidden')) {
        if ($(this).find('#referers').val() > 0) {
          $(this).find('.renamer-updater').show();
        }
        confirmer.show('blind');
        return false;
      }
    });
    $('body').on('click', '.follow-updater', function() {
      return $(this).closest('form').find('#card_update_all_users').val('true');
    });
    $('body').on('submit', '.edit-view.SELF-Xfollow_default .card-form', function() {
      var confirmer;
      confirmer = $(this).find('.confirm_update_all-view');
      if (confirmer.is(':hidden')) {
        $(this).find('.follow-updater').show();
        confirmer.show('blind');
        return false;
      }
    });
    $('body').on('click', 'button.redirecter', function() {
      return window.location = $(this).attr('href');
    });
    if (!wagn.noDoubleClick) {
      $('body').on('dblclick', 'div', function(event) {
        var s, t;
        t = $(this);
        if (t.closest('.nodblclick')[0]) {
          return false;
        }
        if (t.closest('.card-header')[0]) {
          return false;
        }
        s = t.slot();
        if (s.find('.card-editor')[0]) {
          return false;
        }
        if (!s.data('cardId')) {
          return false;
        }
        s.addClass('slotter');
        s.attr('href', wagn.rootPath + '/card/edit/~' + s.data('cardId'));
        $.rails.handleRemote(s);
        return false;
      });
    }
    $('body').on('submit', 'form.slotter', function(event) {
      var input, target;
      if ((target = $(this).attr('main-success')) && $(this).isMain()) {
        input = $(this).find('[name=success]');
        if (input && !(input.val().match(/^REDIRECT/))) {
          return input.val((target === 'REDIRECT' ? target + ': ' + input.val() : target));
        }
      }
    });
    $('body').on('change', '.live-type-field', function() {
      $(this).data('params', $(this).closest('form').serialize());
      return $(this).data('url', $(this).attr('href'));
    });
    $('body').on('change', '.edit-type-field', function() {
      return $(this).closest('form').submit();
    });
    $('body').on('change', '.autosave .card-content', function() {
      var content_field;
      content_field = $(this);
      return setTimeout((function() {
        return content_field.autosave();
      }), 500);
    });
    $('body').on('mouseenter', '[hover_content]', function() {
      $(this).attr('hover_restore', $(this).html());
      return $(this).html($(this).attr('hover_content'));
    });
    $('body').on('mouseleave', '[hover_content]', function() {
      return $(this).html($(this).attr('hover_restore'));
    });
    $('body').on('keyup', '.name-editor input', function() {
      var box, name;
      box = $(this);
      name = box.val();
      return wagn.pingName(name, function(data) {
        var ed, leg, link, msg, qualifier, slot_id, status;
        if (box.val() !== name) {
          return null;
        }
        status = data['status'];
        if (status) {
          ed = box.parent();
          leg = box.closest('fieldset').find('legend');
          msg = leg.find('.name-messages');
          if (!msg[0]) {
            msg = $('<span class="name-messages"></span>');
            leg.append(msg);
          }
          ed.removeClass('real-name virtual-name known-name');
          slot_id = box.slot().data('cardId');
          if (status !== 'unknown' && !(slot_id && parseInt(slot_id) === data['id'])) {
            ed.addClass(status + '-name known-name');
            link = qualifier = status === 'virtual' ? 'in virtual' : 'already in';
            return msg.html('"<a href="' + wagn.rootPath + '/' + data['url_key'] + '">' + name + '</a>" ' + qualifier + ' use');
          } else {
            return msg.html('');
          }
        }
      });
    });
    return $('body').on('click', '.render-error-link', function(event) {
      var msg;
      msg = $(this).closest('.render-error').find('.render-error-message');
      msg.show();
      return event.preventDefault();
    });
  });

  initCaptcha = function(form) {
    var recapDiv, recapUri;
    recapDiv = $("<div class='g-recaptcha' data-sitekey='" + wagn.recaptchaKey + "'></div>");
    $(form).children().last().after(recapDiv);
    recapUri = "https://www.google.com/recaptcha/api.js";
    return $.getScript(recapUri);
  };

  addCaptcha = function(form) {
    var recapDiv;
    recapDiv = $('<div class="g-recaptcha"></div>');
    $(form).children().last().after(recapDiv);
    return grecaptcha.render(recapDiv, {
      sitekey: wagn.recaptchaKey
    });
  };

  snakeCase = function(str) {
    return str.replace(/([a-z])([A-Z])/g, function(match) {
      return match[0] + '_' + match[1].toLowerCase();
    });
  };

  warn = function(stuff) {
    if (typeof console !== "undefined" && console !== null) {
      return console.log(stuff);
    }
  };

}).call(this);