(function() {
  var Sidebar, SidebarFilter, SidebarTemplates, SidebarToolbar,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  jQuery.expr[':'].like = function(el, i, selector) {
    var content, text_to_search;
    if (!selector[3]) {
      return true;
    }
    content = ($(el).data('search') || '').toLowerCase();
    text_to_search = selector[3].toLowerCase();
    return content.indexOf(text_to_search) >= 0;
  };

  Sidebar = (function() {
    var FOLDER_ICONS, HIGHLIGHT_CLASS, ICON_SETS, TOGGLE_ALL_BUTTON_SELECTOR, TOGGLE_SELECTOR;

    FOLDER_ICONS = ['fa-folder-o', 'fa-folder-open-o'];

    ICON_SETS = [FOLDER_ICONS];

    HIGHLIGHT_CLASS = 'current';

    TOGGLE_SELECTOR = '[data-behavior~=toggle]';

    TOGGLE_ALL_BUTTON_SELECTOR = '#cms-sidebar-collapse-all';

    function Sidebar(selector1) {
      this.selector = selector1;
      this.render_content = bind(this.render_content, this);
      this.render_partials = bind(this.render_partials, this);
      this.render_portlets = bind(this.render_portlets, this);
      this.render_layouts = bind(this.render_layouts, this);
      this.resize = bind(this.resize, this);
      this.fire_ajax();
      this.template = new SidebarTemplates();
      this.filter = new SidebarFilter(this);
      this.hook(document);
      $((function(_this) {
        return function() {
          _this.element = $(_this.selector);
          _this.load_resizable();
          return _this.element.on('click', TOGGLE_ALL_BUTTON_SELECTOR, function(event) {
            var all_packed, sections;
            sections = _this.top_level_sections();
            all_packed = _this.all_items_packed();
            if (all_packed) {
              sections.filter('.packed').each(function(_, element) {
                return ThreeScale.Toggle.get(element).unpack();
              });
            } else {
              sections.filter(':not(.packed)').each(function(_, element) {
                return ThreeScale.Toggle.get(element).pack();
              });
            }
            return _this.update_expand_collapse_button(!all_packed);
          }).on('click', TOGGLE_SELECTOR, function(event) {
            var target, ul;
            target = $(event.target);
            if (!target.is('.fa')) {
              return;
            }
            ul = target.siblings('ul');
            if (!ul.length) {
              return;
            }
            ThreeScale.Toggle.get(ul).toggle(300, function(el) {
              return _this.update_expand_collapse_button();
            });
            return false;
          }).on('toggle:pack toggle:unpack', function(event) {
            var class_names, icon, icon_set, j, len, results;
            icon = $(event.target).parent().children('.fa');
            results = [];
            for (j = 0, len = ICON_SETS.length; j < len; j++) {
              icon_set = ICON_SETS[j];
              class_names = _(icon_set).map(function(class_name) {
                return "." + class_name;
              }).join(', ');
              results.push(icon.filter(class_names).toggleClass(icon_set.join(' ')));
            }
            return results;
          });
        };
      })(this));
    }

    Sidebar.prototype.top_level_sections = function() {
      var root_section;
      root_section = $('#cms-sidebar-content ul .cms-section ul:first', this.element);
      return root_section.children(TOGGLE_SELECTOR).children('ul');
    };

    Sidebar.prototype.all_items_packed = function() {
      var packed_sections, top_level_sections;
      top_level_sections = this.top_level_sections();
      packed_sections = top_level_sections.filter('.packed');
      return packed_sections.length === top_level_sections.length;
    };

    Sidebar.prototype.expand_collapse_all_button = function() {
      return this.element.find(TOGGLE_ALL_BUTTON_SELECTOR);
    };

    Sidebar.prototype.update_expand_collapse_button = function(all_packed) {
      if (all_packed == null) {
        all_packed = this.all_items_packed();
      }
      return this.expand_collapse_all_button().html(Sidebar.icon(all_packed ? 'plus-square-o' : 'minus-square-o'));
    };

    Sidebar.prototype.fire_ajax = function() {
      if (this.ajax) {
        this.ajax.abort();
      }
      return this.ajax = $.ajax('/p/admin/cms/templates/sidebar.json').success((function(_this) {
        return function(json) {
          return _this.update(json);
        };
      })(this)).error(function(xhr, status, error) {
        console.error(xhr.status + " " + error);
        return console.error(xhr.responseText);
      });
    };

    Sidebar.prototype.hook = function(element) {
      var selector;
      selector = this.selector;
      element = $(element);
      element.tipsy({
        live: selector + " li > a",
        gravity: $.fn.tipsy.autoWE
      });
      return element.on('cms-sidebar:update', (function(_this) {
        return function(event) {
          ThreeScale.Toggle.loadAndMarkPacked();
          _this.resize();
          _this.filter.filter();
          _this.tooltips();
          _this.update_expand_collapse_button();
          return _this.items('[data-behavior~=drag]').draggable({
            handle: ":not(.cms-section > i:first-child)",
            helper: function(event) {
              var el, list;
              el = $(this);
              list = $('<ul>', {
                "class": 'cms-sidebar-listing'
              }).appendTo(selector);
              return el.clone().width(el.width()).prependTo(list).addClass('dragged')[0];
            },
            revert: 'invalid'
          });
        };
      })(this)).on('pjax:end cms-sidebar:update', (function(_this) {
        return function(event) {
          return _this.highlight(window.location.pathname);
        };
      })(this)).on('pjax:end', function(event) {
        return $(event.target).trigger('cms-template:init');
      }).on('click', '#cms-sidebar .cms-sidebar-listing a', (function(_this) {
        return function(event) {
          return $.pjax.click(event, '#tab-content');
        };
      })(this)).on('mouseenter mouseleave', '.cms-sidebar-listing li > a', function(event) {
        return $(this).parent().toggleClass('ui-state-hover');
      });
    };

    Sidebar.prototype.load_resizable = function() {
      var saved_width, width;
      if (saved_width = Sidebar.stored_width()) {
        width = parseInt(saved_width, 10);
        this.element.width(width);
      }
      return this.element.resizable({
        handles: 'e',
        minWidth: 150,
        maxWidth: 400
      }, {
        create: this.resize,
        resize: this.resize,
        stop: Sidebar.save_width
      });
    };

    Sidebar.stored_width = function() {
      return $.cookie('cms-sidebar-width', {
        path: '/'
      });
    };

    Sidebar.save_width = function(event, ui) {
      return $.cookie('cms-sidebar-width', ui.size.width, {
        expires: 30,
        path: '/'
      });
    };

    Sidebar.prototype.resize = function(event, ui) {
      var available_width, content, parent, ref, width;
      parent = this.element.parent();
      content = parent.find('#tab-content');
      available_width = parent.width();
      width = (ui != null ? (ref = ui.size) != null ? ref.width : void 0 : void 0) || this.element.outerWidth();
      return content.width(available_width - width);
    };

    Sidebar.prototype.highlight = function(path) {
      this.element.find("a." + HIGHLIGHT_CLASS).removeClass(HIGHLIGHT_CLASS);
      return this.element.find("a[href='" + path + "']").addClass(HIGHLIGHT_CLASS);
    };

    Sidebar.prototype.content = function() {
      return this.element.find('#cms-sidebar-content');
    };

    Sidebar.prototype.layouts = function() {
      return this.element.find('#cms-sidebar-layouts');
    };

    Sidebar.prototype.partials = function() {
      return this.element.find('#cms-sidebar-partials');
    };

    Sidebar.prototype.portlets = function() {
      return this.element.find('#cms-sidebar-portlets');
    };

    Sidebar.prototype.listings = function() {
      return this.element.find('.cms-sidebar-listing');
    };

    Sidebar.prototype.items = function(filter) {
      var items;
      items = this.listings().find('li');
      if (filter != null) {
        return items.filter(filter);
      } else {
        return items;
      }
    };

    Sidebar.prototype.update = function(json) {
      var content, layouts, partials, portlets;
      this.groups = this.group(json);
      this.json = json;
      content = this.render_content(json.root.section);
      layouts = this.render_layouts(this.json.layouts);
      partials = this.render_partials(this.json.partials);
      portlets = this.render_portlets(this.json.portlets);
      return $((function(_this) {
        return function() {
          _this.content().html(content);
          _this.layouts().html(layouts);
          _this.partials().html(partials);
          _this.portlets().html(portlets);
          return _this.element.trigger('cms-sidebar:update');
        };
      })(this));
    };

    Sidebar.prototype.tooltips = function() {
      return this.items('[title]').tipsy({
        gravity: $.fn.tipsy.autoWE
      });
    };

    Sidebar.prototype.group = function(json) {
      var parent_id, section_id;
      section_id = function(p) {
        return p.section_id;
      };
      parent_id = function(s) {
        return s.parent_id;
      };
      return {
        sections: _(json.sections).groupBy(parent_id),
        pages: _(json.pages).groupBy(section_id),
        files: _(json.files).groupBy(section_id),
        builtins: _(json.builtins).groupBy(section_id)
      };
    };

    Sidebar.prototype.render_layouts = function(layouts) {
      var data;
      data = {
        layouts: this.json.layouts
      };
      return this.template.layouts(data);
    };

    Sidebar.prototype.render_portlets = function(portlets) {
      var data;
      data = {
        portlets: this.json.portlets
      };
      return this.template.portlets(data);
    };

    Sidebar.prototype.render_partials = function(partials) {
      var data;
      data = {
        partials: this.json.partials
      };
      return this.template.partials(data);
    };

    Sidebar.prototype.render_content = function(section) {
      var all, data, section_id;
      section_id = section.id;
      data = {
        section: section,
        sections: this.groups.sections[section_id],
        pages: this.groups.pages[section_id],
        files: this.groups.files[section_id],
        builtins: this.groups.builtins[section_id],
        render: this.render_content
      };
      all = _.union(data.sections || [], data.pages || [], data.files || [], data.builtins || []);
      section.empty = _(all).isEmpty();
      if (section.parent_id || section.rendered) {
        return this.template.content(data);
      } else {
        section.rendered = true;
        return this.template.root(data);
      }
    };

    Sidebar.html = function(element) {
      return element.clone().wrap('<div>').parent().html();
    };

    Sidebar.link_to = function(text, path, title) {
      if (title == null) {
        title = text;
      }
      if (title === null) {
        title = " ";
      }
      if (typeof title !== 'string') {
        title = title.join(' ');
      }
      return Sidebar.html($('<a>', {
        text: text,
        href: path,
        title: title
      }));
    };

    Sidebar.icon = function(icon, text) {
      text = text != null ? " " + text : '';
      return Sidebar.html($('<i>', {
        "class": "fa fa-" + icon + " fa-fw"
      })) + text;
    };

    Sidebar.icon_link_to = function(icon, text, path, title) {
      var link;
      if (title == null) {
        title = text;
      }
      icon = Sidebar.icon(icon);
      link = Sidebar.link_to(text, path, title);
      return Sidebar.html($(link).prepend(icon + ' '));
    };

    Sidebar.search = function(item) {
      return " data-search=\"" + item.search.string + "\" data-type=\"" + item.search.type + "\" data-origin=\"" + item.search.origin + "\" ";
    };

    return Sidebar;

  })();

  SidebarToolbar = (function() {
    var ACTIVE;

    ACTIVE = 'active';

    function SidebarToolbar(filter1) {
      this.filter = filter1;
      this.process_origin = bind(this.process_origin, this);
      this.process_type = bind(this.process_type, this);
      $(document).on('click', '[data-filter-type]', this.process_type);
      $(document).on('click', '[data-filter-origin]', this.process_origin);
      $((function(_this) {
        return function() {
          var j, len, origin, type, types;
          types = _this.filter.status.types;
          if (!types || (types != null ? types.length : void 0) === 0) {
            types = ['all'];
          }
          for (j = 0, len = types.length; j < len; j++) {
            type = types[j];
            $("[data-filter-type=" + type + "]").addClass(ACTIVE);
          }
          if (origin = _this.filter.status.origin || 'own') {
            return $("[data-filter-origin=" + origin + "]").addClass(ACTIVE);
          }
        };
      })(this));
    }

    SidebarToolbar.prototype.process_type = function(event) {
      var all, element, items, type;
      element = $(event.currentTarget);
      type = element.data('filter-type');
      items = element.siblings();
      all = items.filter('[data-filter-type=all]');
      if (this.filter.type(type)) {
        element.toggleClass(ACTIVE);
        return all.removeClass(ACTIVE);
      } else {
        items.removeClass(ACTIVE);
        if (element.data('filter-type') === 'all') {
          return element.addClass(ACTIVE);
        } else {
          element.removeClass(ACTIVE);
          return all.addClass(ACTIVE);
        }
      }
    };

    SidebarToolbar.prototype.process_origin = function(event) {
      var element, origin;
      element = $(event.currentTarget);
      origin = element.data('filter-origin');
      this.filter.origin(origin);
      return element.addClass('active').siblings().removeClass('active');
    };

    return SidebarToolbar;

  })();

  SidebarFilter = (function() {
    var ALL, CMS_FILTER_COOKIE_NAME, INPUT;

    CMS_FILTER_COOKIE_NAME = 'cms-filter-string';

    INPUT = '#cms-filter input';

    ALL = 'all';

    SidebarFilter.serialized_status = function() {
      return $.cookie(CMS_FILTER_COOKIE_NAME, {
        path: '/'
      }) || '{}';
    };

    SidebarFilter.load = function() {
      return this.status || (this.status = JSON.parse(this.serialized_status()));
    };

    SidebarFilter.save = function(status) {
      var json;
      this.status = status;
      json = JSON.stringify(status);
      return $.cookie(CMS_FILTER_COOKIE_NAME, json, {
        expires: 30,
        path: '/'
      });
    };

    function SidebarFilter(sidebar) {
      var query;
      this.sidebar = sidebar;
      this.status = SidebarFilter.load();
      this.toolbar = new SidebarToolbar(this);
      $(document).on('keyup change search click', INPUT, (function(_this) {
        return function(event) {
          var text;
          text = event.currentTarget.value;
          return _this.search(text);
        };
      })(this));
      if (query = this.status.query) {
        $((function(_this) {
          return function() {
            return $(INPUT).val(query);
          };
        })(this));
      }
    }

    SidebarFilter.prototype.save = function() {
      return SidebarFilter.save(this.status);
    };

    SidebarFilter.prototype.filter = function() {
      var items, listings, matched, not_matched, origin, query, type, types;
      items = this.sidebar.items('[data-behavior~="search"]');
      items.removeClass('matched not-matched');
      matched = items;
      if (query = this.status.query) {
        matched = matched.filter(":like(" + query + ")");
      }
      types = (function() {
        var j, len, ref, results;
        ref = this.status.types || [];
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          type = ref[j];
          results.push(matched.filter("[data-type~=" + type + "]").toArray());
        }
        return results;
      }).call(this);
      if (types.length > 0) {
        matched = $(_(matched.toArray()).intersection(_.union.apply(_, types)));
      }
      if (origin = this.status.origin) {
        matched = matched.filter("[data-origin~=" + origin + "]");
      }
      matched.show().addClass('matched');
      not_matched = _(items.toArray()).difference(matched.toArray());
      $(not_matched).hide().addClass('not-matched');
      items.filter('.cms-section:has(.matched)').show();
      listings = this.sidebar.listings().removeClass('empty');
      return listings.filter(':not(:has(.matched))').addClass('empty');
    };

    SidebarFilter.prototype.type = function(type) {
      var base, index, types;
      types = (base = this.status).types || (base.types = []);
      index = types.indexOf(type);
      if (type === ALL) {
        types = [];
      } else if (index >= 0) {
        types.splice(index, 1);
      } else {
        types.push(type);
      }
      this.status.types = types;
      this.filter();
      this.save();
      return types.length > 0;
    };

    SidebarFilter.prototype.origin = function(origin) {
      if (origin === ALL) {
        origin = null;
      }
      this.status.origin = origin;
      this.filter();
      return this.save();
    };

    SidebarFilter.prototype.search = function(string) {
      if (string === "") {
        delete this.status.query;
      } else {
        this.status.query = string;
      }
      this.filter();
      return this.save();
    };

    return SidebarFilter;

  })();

  SidebarTemplates = (function() {
    function SidebarTemplates() {}

    SidebarTemplates.root = "<style>\n  html {\n    // So that the the scrollbar does not\n    // turn on/off while filtering.\n    overflow: -moz-scrollbars-vertical;\n    overflow-y: scroll;\n  }\n</style>\n\n<ul>\n  <li class=\"cms-section\" data-behavior=\"toggle search\">\n    <span id=\"cms-sidebar-collapse-all\" class=\"collapse-button\"><i class=\"folder-open-o fa-fw\"></i></span>\n    <%= link_to(section.title, section.edit_path) %>\n    <%= render(section) %>\n  </li>\n  <li class=\"no-results\">No Content Found</li>\n</ul>";

    SidebarTemplates.content = "<ul id=\"cms-sidebar-section-<%= section.id %>\">\n  <% _.each(pages, function(page) { %>\n    <li class=\"cms-page\" data-id=\"<%= page.id %>\" data-behavior=\"drag search\" data-param=\"cms_page\" <%= search(page) %>>\n      <%= icon_link_to('file-o', page.title, page.edit_path, [ page.path, '(' + page.title + ')' ]) %>\n    </li>\n  <% }); %>\n\n  <% _.each(files, function(file) { %>\n    <li class=\"cms-file\" data-id=\"<%= file.id %>\" data-behavior=\"drag search\" data-param=\"cms_file\" <%= search(file) %>>\n      <%= icon_link_to('paperclip', file.attachment_file_name, file.edit_path) %>\n    </li>\n  <% }); %>\n\n  <% _.each(builtins, function(builtin) { %>\n    <li class=\"cms-builtin\" data-id=\"<%= builtin.id %>\" data-behavior=\"drag search\" data-param=\"cms_builtin\" <%= search(builtin) %>>\n      <%= icon_link_to('cog', builtin.title, builtin.edit_path) %>\n    </li>\n  <% }); %>\n\n  <% _.each(sections, function(section){ %>\n    <li class=\"cms-section\"  data-id=\"<%= section.id %>\" data-behavior=\"toggle drag search\" data-param=\"cms_section\" <%= search(section) %>>\n      <%= icon('folder-open-o fa-fw') %>\n      <%= link_to(section.title, section.edit_path) %>\n      <%= render(section) %>\n    </li>\n  <% });  %>\n</ul>";

    SidebarTemplates.layouts = "<h3>Layouts</h3>\n<ul>\n <% _.each(layouts, function(layout) { %>\n   <li <%= search(layout) %> data-behavior=\"search\">\n     <%= icon_link_to('code', layout.title, layout.edit_path) %>\n    </li>\n <% }); %>\n <% if(_.isEmpty(layouts)) { %><li data-behavior=\"search\">No Layouts</li><% }; %>\n <li class=\"no-results\">No Layouts Found</li>\n</ul>";

    SidebarTemplates.portlets = "<h3>Portlets</h3>\n<ul>\n  <% _.each(portlets, function(portlet) { %>\n    <li <%= search(portlet) %>>\n      <%= icon_link_to('rocket', portlet.title, portlet.edit_path) %>\n    </li>\n  <% }); %>\n  <% if(_.isEmpty(portlets)) { %><li data-behavior=\"search\">No Portlets</li><% }; %>\n  <li class=\"no-results\">No Portlets Found</li>\n</ul>\n";

    SidebarTemplates.partials = "<h3>Partials</h3>\n<ul>\n  <% _.each(partials, function(partial) { %>\n    <li <%= search(partial) %> data-behavior=\"search\">\n      <%= icon_link_to('puzzle-piece', partial.system_name, partial.edit_path) %>\n    </li>\n  <% }); %>\n  <% if(_.isEmpty(partials)) { %><li data-behavior=\"search\">No Partials</li><% }; %>\n  <li class=\"no-results\">No Partials Found</li>\n</ul>";

    SidebarTemplates.helpers = function(template) {
      var helpers;
      helpers = {
        link_to: Sidebar.link_to,
        icon: Sidebar.icon,
        icon_link_to: Sidebar.icon_link_to,
        search: Sidebar.search
      };
      return function(data) {
        $.extend(data, helpers);
        return template(data);
      };
    };

    SidebarTemplates.template = function(source) {
      return this.helpers(_.template(source));
    };

    SidebarTemplates.prototype.content = SidebarTemplates.template(SidebarTemplates.content);

    SidebarTemplates.prototype.root = SidebarTemplates.template(SidebarTemplates.root);

    SidebarTemplates.prototype.layouts = SidebarTemplates.template(SidebarTemplates.layouts);

    SidebarTemplates.prototype.portlets = SidebarTemplates.template(SidebarTemplates.portlets);

    SidebarTemplates.prototype.partials = SidebarTemplates.template(SidebarTemplates.partials);

    return SidebarTemplates;

  })();

  window.ThreeScale.Sidebar = Sidebar;

}).call(this);
