(function($){

$.fn.autoGrowInputInvite = function(o)
{
	o = $.extend({
			maxWidth: 1000,
			minWidth: 0,
			comfortZone: 12,
			active: true
		}, o);

	this.filter('input:text').each(function(){

		var minWidth = o.minWidth || $(this).width(),
		val = '',
		input = $(this),
		testSubject = $('<tester/>').css({
			position: 'absolute',
			top: -9999,
			left: -9999,
			width: 'auto',
			fontSize: input.css('fontSize'),
			fontFamily: input.css('fontFamily'),
			fontWeight: input.css('fontWeight'),
			letterSpacing: input.css('letterSpacing'),
			whiteSpace: 'nowrap'
		}),
		check = function() {

			if (val === (val = input.val())) {return;}

			// Enter new content into testSubject
			var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;');
			testSubject.html(escaped);

			// Calculate new width + whether to change
			var testerWidth = testSubject.width(),
			newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
			currentWidth = input.width(),
			isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) || (newWidth > minWidth && newWidth < o.maxWidth);

			// Animate width
			if (isValidWidthChange) {
				input.width(newWidth);
			}

		};

		testSubject.insertAfter(input);

		if (o.active) $(this).bind('keyup keydown blur update', check);

	});

	return this;
};

$.fn.bindAutocompleteInvite = function(url, $realInput, defaultEntry)
{
	function addEntry(name, id)
	{
		
		if ($realInput.val() == '') {$realInput.val(id);}
		else {$realInput.val($realInput.val() + ', ' + id);}
		
		$('span.ui-autocomplete-x').live('click', function()
		{
			removeEntry($(this));
		});
		
		return '<span class="ui-autocomplete-person invite"><span class="ui-autocomplete-name" >'
						+ name
						+ '</span><span class="ui-autocomplete-id" style="display:none;">'
						+ id
						+ '</span><span class="ui-autocomplete-x">X</span></span>';
	}
	
	function removeEntry(target)
	{
		var $cont = target.parent();
		var $input = $cont.siblings('div.ui-autocomplete-input').children('input');
		var id = $cont.children('span.ui-autocomplete-id').text();
		var val = $realInput.val().split(', ');

		for (i=0; i<val.length; i++)
		{
			if (val[i] == id)
			{
				val.splice(i, 1);
				break;
			}
		}

		$realInput.val(val.join(', '));

		$cont.remove();
		$input.focus();
	}
	
	this.autoGrowInputInvite();

	// to move between entries
	$(this).bind('keydown', function(event)
	{
		var entries = $(this).parent().prevAll('.ui-autocomplete-person');
		
		var current = entries.filter('.selected').length == 0 ? undefined : entries.filter('.selected');
		
		if (event.keyCode === $.ui.keyCode.ENTER && $(this).val() !== '')
		{
			event.stopPropagation();

			return false;
		}
		
		if ((event.keyCode === $.ui.keyCode.BACKSPACE || event.keyCode === $.ui.keyCode.DELETE) && $(this).val() === '')
		{
			// select/delete last entry
			if (current === undefined) current = entries.first();
			
			if (current.hasClass('ui-state-active'))
			{
				removeEntry(current.children('span.ui-autocomplete-x'));
			}
			else
			{
				current.addClass('ui-state-active');
			}
			
			return false;
		}
		else
		{
			if (current === undefined) return;
			if (current.hasClass('.ui-state-active')) current.removeClass('.ui-state-active');
		}
	});
	
	var selected;
	var acConfig = {
		source:  url,
		//minLength: 3,
		open: function(event, ui)
		{
			// show default if no results
			if ($(menu.element).children().length == 0)
			{
				$(menu.element).hide();
				
				return;
			}
			
			// freeze the position
			$container = $(this).parent().parent();
			
			$(menu.element).position({
				my: 'left top',
				at: 'left bottom',
				of: $container
			}).outerWidth($container.outerWidth());
			
			// focus the first menu element
			menu.activate($.Event({type: "mouseenter"}), menu.element.children().first());
		},
		focus: function(event, ui)
		{
			return false;
		},
		select: function(event, ui)
		{
			selected = ui.item;
			
			var selUId = selected.UserId;
		},
		close: function(event, ui)
		{
			// if nothing was selected, return
			if (selected === undefined || selected.value != $(this).val()) return;

			// clear the input
			$(this).val('');

			// add new entry
			var newEntry = addEntry(selected.value, selected.UserId);
			$('#selectedPeople').after($(newEntry));
			
			selected = undefined;
		}
	};
	
	this.bind('focusout', function(event)
	{
		// clear the input
		$(this).val('');
	})
	
	$data = this.autocomplete(acConfig).data("autocomplete");

	$data._menuResize = function ()
	{
		var a = this.menu.element;
		a.outerWidth(Math.max(a.width("").outerWidth(), this.element.outerWidth()));
	}

	$data._renderItem = function(ul, item)
	{
		var val = $realInput.val().split(', ');
		for (i=0; i<val.length; i++)
		{
			if (val[i] == item.UserId)
			return;
		}
		
		li = $('<li></li>')
			.data("item.autocomplete", item)
			.append('<a><div><img class="ui-menu-item" src="' + item.Img + '" /></div><div><span>' + item.value + '</span>'
				+ '<span class="ui-autocomplete-role">' + item.Ruolo + '</span></div></a>')
			.appendTo(ul);
		li.width(parseInt(li.parent("ul.ui-menu").prev("div.ui-autocomplete-container").width()) - parseInt($(".ui-menu").css('padding-left')) - parseInt($(".ui-menu").css('padding-right')));
		return li;
	};
	
	var menu = $data.menu;
	
	// if there's a default name, adds it
	if (defaultEntry !== null)
	{
		// decode eventual url
		var cTable = [
			['%20', ' '],
			['+', ' ']
		];
		
		// Split so you can send to more than 1 person
		var entries = defaultEntry.split(';');
		
		$.each( entries, function( entryIndex, entryValue ) {

			$.each(cTable, function(i, elem)
			{
				entryValue = entryValue.split(elem[0]);
				entryValue = entryValue.join(elem[1]);
			})
			
			// default entry
			var entryName = entryValue.split('_')[0];
			var entryId = entryValue.split('_')[1];
		
			$('#selectedPeople').after(addEntry(entryName, entryId));
			
		});

	}
	else
	{
		defaultEntry = '';
	}
	
	return this;
}

$.fn.peopleAutocompleteInvite = function(o)
{
	o = $.extend({
		url: null,
		defaultEntry: null,
		disabled: null
	}, o);
	
	if (o.url === null)
	{
		$.error('ERROR: autocopmlete - please provide an url!');
	}
	
	var autocompleteId = 0;
	
	var inputName = $(this).attr('name');
	var inputId = $(this).attr('id');

	$(this).attr({id: ''}).before('<input id="' + inputId + '" name="' + inputName + '" type="hidden" />')
		.after('<input class="ui-autocomplete ui-autocompletePeople" type="text" />');
	
	$('input.ui-autocompletePeople').wrap('<div class="ui-autocomplete-container"><div class="ui-autocomplete-input"></div></div>');

	$(this).remove();

	
	var binded = false;
	$('div.ui-autocomplete-container').live('click', function()
	{
		var $input = $(this).children('.ui-autocomplete-input').children('input.ui-autocomplete');
		if (!binded) $input.bindAutocompleteInvite(o.url, $('input#' + inputId), o.defaultEntry);
		$input.focus();
		autocompleteId++;
		binded = true;
	}).click();

	if ( o.disabled == 1 )
		$('div#msgRcpts').hide();
	
	return this;
}

})(jQuery);
