Drupal.checkPlain = function (text) {
  return text.replace('&', '&amp;')
             .replace('<', '&lt;')
             .replace('"', '&quot;')
             .replace(/^\s+/g, '')
             .replace(/\s+$/g, '')
             .replace('\n', '<br />');
}

Drupal.serialize = function (data, prefix) {
  prefix = prefix || '';
  var out = '';
  for (i in data) {
    var name = prefix.length ? (prefix +'[' + i +']') : i;
    if (out.length) out += '&';
    if (typeof data[i] == 'object') {
      out += Drupal.serialize(data[i], name);
    }
    else {
      out += name +'=';
      out += Drupal.encodeURIComponent(data[i]);
    }
  }
  return out;
}

if (Drupal.jsEnabled) {
  $(document).ready(function () {
    // Note: all tag fields are autocompleted, and have already been initialized at this point.
	$('#community-tags-form').hide(); //I'm hiding the whole form, so the submit button does not show
    $('input.form-tags').each(function () {
      // Hide submit buttons.
      $('input[@type=submit]', this.form).hide();

      // Fetch settings.
      var o = Drupal.settings.communityTags;
	  var p = Drupal.settings.community_tags_reload;
      var sequence = 0;
	  
	  //alert(o.tags);

      // Patch for drupal_to_js() bug in Drupal 5.1
      if (typeof o.tags.push == 'undefined') {
        o.tags = [];
      }

      // Show the textfield and empty its value.
      var textfield = $(this).val('').css('display', 'inline');

      // Prepare the add Ajax handler and add the button.
      var addHandler = function () {
		loading(); //if it updates the list, update the tags as well
	  	var nid = $("input[@id='edit-refer-nid']").val();
	  	if (isArray(o.url)) {
			for (key in o.url) {
				node = o.url[key].replace('/index.php?q=community-tags/js/','');
				if (node == nid) {
					var url = o.url[key];
					//alert(url);
				}
			}
		} else {
			var url = o.url;
		}
		
        $.post(url, Drupal.serialize({ sequence: ++sequence, tags: o.tags, add: textfield[0].value }), function (data) {
          data = Drupal.parseJson(data);
          if (data.status && sequence == data.sequence) {
            o.tags = data.tags;
			updateTags(); //if it updates the list, update the tags as well
          }
        });

        // Add tag to local list
        o.tags.push(textfield[0].value);
        o.tags.sort(function (a,b) { a = a.toLowerCase(); b = b.toLowerCase(); return (a>b) ? 1 : (a<b) ? -1 : 0; });
		updateList();
        
        // Clear field and focus it.
        textfield.val('').focus();

      };
	  //alert(o.add);
	  	if (isArray(o.url)) {
			var addname = o.add[0];
		} else {
			var addname = o.add;
		}
      var button = $('<input type="button" class="form-button" value="'+ Drupal.checkPlain(addname) +'" />').click(addHandler);
      $(this.form).submit(function () { addHandler(); return false; });

      // Prepare the delete Ajax handler.
      var deleteHandler = function () {
		  loading(); //if it updates the list, update the tags as well
		  var nid = $("input[@id='edit-refer-nid']").val();
        // Remove tag from local list.
		//alert($(this).attr('key'));
        var i = $(this).attr('key');
        o.tags.splice(i, 1);
		updateList();
		
	  	var nid = $("input[@id='edit-refer-nid']").val();
	  	if (isArray(o.url)) {
			for (key in o.url) {
				node = o.url[key].replace('/index.php?q=community-tags/js/','');
				if (node == nid) {
					var url = o.url[key];
					//alert(url);
				}
			}
		} else {
			var url = o.url;
		}
        $.post(url, Drupal.serialize({ sequence: ++sequence, tags: o.tags, add: '' }), function (data) {
          data = Drupal.parseJson(data);
          if (data.status && sequence == data.sequence) {
            o.tags = data.tags;
			//alert(o.tags);
			updateTags(); //if it updates the list, update the tags as well
          }
        });

        // Clear textfield and focus it.
        textfield.val('').focus();
      };

      // Callback to update the tag list.
      function updateList() {
		 //alert(nid);
        list.empty();
        for (i in o.tags) {
		  //alert(o.tags[i]);
          list.append('<li key="'+ Drupal.checkPlain(i) +'">'+ Drupal.checkPlain(o.tags[i]) +'</li>');
        }
        $('li', list).click(deleteHandler);	
      }
	  
	  function loading() {
		  var message = $("div[@id='community_tags_cloud']");
		  var url="http://"+window.location.hostname;
		  message.html('Reloading Tags. <img src="'+url+'/misc/ajax-loader-squares.gif" />');
	  }
	  
	  function updateTags() {
		  var nid = $("input[@id='edit-refer-nid']").val();
		  var message = $("div[@id='community_tags_cloud']");
		  
			 if (isArray(p.url)) {
				var url = p.url[0];
			} else {
				var url = p.url;
			}
		$.getJSON(url,
        {nid:nid},
         function (data) {
           	message.html(data.msg);
         }); 
	  }
	  
		function isArray(obj) {
			return obj.constructor == Array;
		}


      // Create widget markup.
      var widget = $('<div class="tag-widget"><ul class="inline-tags clear-block"></ul></div>');
      textfield.before(widget);
      widget.append(textfield).append(button);
      var list = $('ul', widget);
	  $('#community-tags-form').show(); //I'm hiding the whole form, so the submit button does not show
	  updateList();
	  //updateTags();
    });
  });
}