--- suggestedterms.js	Fri Dec 14 07:15:54 2007
+++ suggestedterms.js	Sun Jan 06 21:09:41 2008
@@ -3,22 +3,62 @@
 }
 
 function suggestedterms_build_links() {
+  var seperator = ', ';
+  var selectedClass = 'selected';
+  var input;
+  
   // get all attributes of span tag
   $('span.suggestedterm').each ( function() {
+  
+    // save reference to the input field
+    if(!input) {
+	  input = $(this).parent().siblings('input');
+    }
+	
     var a = $("<a>" + $(this).text() + "</a>")
     .attr('href', '#')
     .addClass($(this).attr('class'))
     .bind('click', function(event) {
       event.preventDefault();
-      var input = $(this).parent().siblings('input');
-      var text = $(this).text();
-      if (((', ' + input.val() + ',').indexOf(', ' + text + ',') < 0) && ((', ' + input.val() + ',').indexOf(', "' + text + '",') < 0)) {
-        if ((input.val()).length > 0) {
-          input.val(input.val() + ', ');
+      $(this).toggleClass(selectedClass);
+	  var text = $(this).text();
+	  var val = input.val();
+	  
+	  // add term
+      if (((seperator + val + ',').indexOf(seperator + text + ',') < 0) && ((seperator + val + ',').indexOf(', "' + text + '",') < 0)) {
+        if ((val).length > 0) {
+          val += seperator;
         }
-        input.val(input.val() + text);
+        val += text;
       }
-    }); // end bind
+	  
+	  // remove term
+	  else {
+	  
+	    val = val.replace(text + seperator, '').replace(text, '');
+		
+		// remove any seperator at the begining of the string
+		if (val.indexOf(seperator) == 0) {
+	      val = val.substr(seperator.length, val.length);
+	    }		
+		
+		// remove any seperator at end of the string
+	    if (val.lastIndexOf(seperator) == val.length - seperator.length) {
+	      val = val.substr(0, val.lastIndexOf(seperator));
+	    }
+	    
+	  }
+	  
+	  // update the input field with the new value
+	  input.val(val);
+	  
+    }); // end bind	
+	
+	// add selected class to already selected terms
+	if (input.val().indexOf($(this).text()) != -1) {
+		a.addClass(selectedClass);
+    }
+	  
     $(this).before(a).remove();
   }); // end span.suggestedterm
 } // end build_links
