 # -@tags -> @graduated_tags
 # -info -> weight
 # -info.weight -> weight
+# -'TODO's indicate case-specific changes
 ###
-
 _.extend( Template.tagbox,
-
+  add_tag: (tags, tag_text, event, id) =>
+    console.log(tags, tag_text, event, id)
+    if tag_text != "" #TODO: && not @my_tags[tag_text]?
+      #TODO: add to @my_tags not @tags
+      tags[tag_text] ?= { users: [], weight: 0}
+      tags[tag_text].users.push(Session.get('user_id'))
+      Posts.update(id, {$set: {tags: tags}})
+      #clear textbox and update suggestion filter
+      event.target.value = ''
+      Session.set("filter_text_#{ id }", '')
+      Session.get("context_#{ id }").invalidate()
+    
   visible_tags: ->
     visible = (tag for tag of @tags)  #graduated tags
-    @my_tags ?= {}                    #REMOVE on schema change
+    @my_tags ?= {}                    #TODO: REMOVE on schema change
     for name of @my_tags              #my tags
       if not (name in visible)
         visible.push(name)
     return visible
     
-  suggested_tags: -> Session.get("suggestions_#{ @_id }")
-    
+  suggested_tags: -> 
+    suggestions = Session.get("suggestions_#{ @_id }")
+    filtered = []
+    for tag in suggestions
+      filtered.push(tag) if tag? &&
+        tag.search(Session.get("filter_text_#{ @_id }")) != -1
+    return filtered
+
   tagging_post: -> Session.equals("tagging_#{ @_id }", true)
   
   events: {
-    'load': ->
+    ###
     'focus .suggested': (event) ->
       if not event.isImmediatePropagationStopped()
         #console.log(event.target,"clicked")
         #event.target.focus()
 
         event.stopImmediatePropagation()
-        
+    ###
+    ###
     'keydown .suggested': (event) ->
       if not event.isImmediatePropagationStopped()
         tag_text = event.target.innerText

)

Handlebars.registerHelper('vis_tags', (context, object) ->
  @my_tags = {test: 0}          #REMOVE
  ret = ""
  for tag in context
    ret += "<div class='tag"

    ret += " suggested' tabindex='0'>" + tag + "</form>"
  return ret
)
