(function($) {

	$.fn.tagit = function(options) {

		var el = this;

		BACKSPACE		= 8;
		ENTER			= 13;
		SPACE			= 32;
		COMMA			= 44;

		// add the tagit CSS class.
		el.addClass("tagit");

		// create the input field.
		var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" id=\""+options.field_name+"\" type=\"text\" /></li>\n";
		el.html (html_input_field);


		$(this).click(function(e){
			if (e.target.tagName == 'A') {
				// Removes a tag when the little 'x' is clicked.
				// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
				remove($(e.target).parent());
				$(e.target).parent().remove();
				if (!options.multipleselections) {
					var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" id=\""+options.field_name+"\" type=\"text\" /></li>\n";
					el.html (html_input_field);
				}
			}
			else {
				// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
				// This is needed because the input field needs to be of a small size.
				el.children(".tagit-new").children(".tagit-input#"+options.field_name).focus();
			}
		});

		remove = function(value) {
			$.ajax({
                'url' : options.url_remove,
                'dataType' : 'json',
                'data' : { 'term' : value.text() },
                'async' : false
            });
		}

		el.children(".tagit-new").children(".tagit-input#"+options.field_name).keypress(function(event){
			if (event.which == BACKSPACE) {
				if (el.children(".tagit-new").children(".tagit-input#"+options.field_name).val() == "") {
					// When backspace is pressed, the last tag is deleted.
					remove($(el).children(".tagit-choice:last"));
					$(el).children(".tagit-choice:last").remove();
					if (!options.multipleselections) {
						var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" id=\""+options.field_name+"\" type=\"text\" /></li>\n";
						el.html (html_input_field);
					}
				}
			}
			// Comma/Space/Enter are all valid delimiters for new tags.
			else if ((event.which == COMMA || event.which == ENTER) && !options.disabledNewTags ) {
				event.preventDefault();

				var typed = el.children(".tagit-new").children(".tagit-input#"+options.field_name).val();
				typed = typed.replace(/,+$/,"");
				typed = typed.trim();

				if (typed != "") {
					if (is_new (typed)) {
						if (options.multipleselections || (countItems() <1 )) {
							create_choice (typed);
						}
					}
					// Cleaning the input.
					el.children(".tagit-new").children(".tagit-input#"+options.field_name).val("");
				}
			}
		});


		el.children(".tagit-new").children(".tagit-input#"+options.field_name).autocomplete({
			source: function(req,data) {
			  var cleanUrl = options.url.indexOf("?") > -1 ? options.url + '&' : options.url + '?';
				jQuery.getJSON(cleanUrl+options.params,req, data)
			},
			select: function(event,ui){
				if (is_new (ui.item)) {
					if (options.multipleselections || (countItems() <1 )) {
						create_choice (ui.item);
					}
				}
				// Cleaning the input.
				el.children(".tagit-new").children(".tagit-input#"+options.field_name).val("");

				// Preventing the tag input to be update with the chosen value.
				return false;
			}

		});

		function is_new (item){
			var is_new = true;
			el.children(".tagit-new").children(".tagit-input#"+options.field_name).parents("ul").children(".tagit-choice").each(function(i){
				n = el.children("input").val();
				if (item.label == n) {
					is_new = false;
				}
			})
			return is_new;
		}
		function create_choice (item){
			var elem = "";
			elem  = "<li class=\"tagit-choice\">\n";
			elem += item.label + "\n";
			elem += "<a class=\"close\">x</a>\n";
			elem += "</li>\n";
			elem += "<input type=\"hidden\" style=\"display:none;\" value=\""+item.value+"\" name=\""+options.field_name+"\">\n";

			if (options.multipleselections) {
				var li_search_tags = el.children(".tagit-new").children(".tagit-input#"+options.field_name).parent();
				$(elem).insertBefore (li_search_tags);
				el.children(".tagit-new").children(".tagit-input#"+options.field_name).val("");
			} else {
				$(el).html(elem);
			}

			if (options.url_new != null) {
				$.ajax({
	                'url' : options.url_new,
	                'dataType' : 'json',
	                'data' : { 'term' : item.value },
	                'async' : false
	            });
			}
		}

		function countItems() {
			var items = $("input[name="+options.field_name+"]");
			return items.length;
		}
	};

	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	};

})(jQuery);

