     }
     """
     boilerplate + "\n"+ (typeStyle(k,v) for k,v of @options.types).join("\n")
-      
+
   # Takes a structure something like:
   #
   #     [

    throw new Exception 'GlyphTree requires jQuery (or a compatible clone).'
  new GlyphTree(e)

root.glyphtree.options = defaults  

class GlyphTree
  
  constructor: (@element) ->
    @options = root.glyphtree.options
    randomId = Math.floor(Math.random()*Math.pow(2,32)).toString(16)
    @idClass = @options.classPrefix+'id'+randomId
    $(@element).addClass(@idClass)
    
    this.setupStyle()
  
  setupStyle: () ->
    $style = $('<style/>')
    $style.attr('type', 'text/css')
    $style.text(this.getStyle())
    $('body').append($style)
    
  getStyle: () ->
    cr = new ClassResolver(@options.classPrefix)
    # Produce style rules for each type

  #
  load: (structure) ->
    cr = new ClassResolver(@options.classPrefix)
    @rootNodes = new NodeContainer(new Node(root, cr) for root in structure, cr)
    @render()
    this

  # Render the container
  render: () ->
    $(@element).empty()
    $(@element).append(@rootNodes.element())
    this

  class Node

    constructor: (struct, classResolver) ->
      @cr = classResolver
      @id = struct.id
      @name = struct.name
      @type = struct.type
      @attributes = struct.attributes
      children = if struct.children
        (new Node(child, classResolver) for child in struct.children)
      else
        []
      @children = new NodeContainer(children, classResolver)

    element: () ->
      @_element ||= @_buildElement()

    _buildElement: () ->
      $li = $("<li/>")
      $li.text(@name)
      $li.addClass(@cr.node())
      $li.addClass(@cr.type(@type ? 'default'))
      if @children.empty()
        $li.addClass(@cr.state('leaf'))
      else
        expandedClass = @cr.state('expanded')
        $li.click (e) ->
          if this == e.target
            $(this).toggleClass(expandedClass)
        $li.append(@children.element())
      $li

  class NodeContainer

    constructor: (@nodes, @cr) ->

    empty: () -> @nodes.length == 0

    element: () ->
      @_element ||= @_buildElement()

    _buildElement: () ->
      $list = $("<ul/>")
      $list.addClass(@cr.tree())
      $list.append(node.element() for node in @nodes)
      $list

  # Handles resolution of DOM classes
  class ClassResolver
    constructor: (@prefix) ->

    node: () -> @prefix + "node"
    tree: () -> @prefix + "tree"
    type: (type) -> @prefix + 'type-' + type
