/*! jQuery.autocompleteFB */
jQuery.fn.autocompleteFB = function (settings) {

	settings = jQuery.extend({
		resource  : [''],
		inputName : 'ACFB_Input',
		acOptions : {}
	}, settings);
	
	var self = this;
	
	//Setup click events for any existing names
	$('.acfb-data img', self).click(function () {
		removeData(this);
	});
	
	//Setup autocomplete
	$('.acfb-input', self).autocomplete(settings.resource,settings.acOptions);
	
	//Setup result()
	//This adds the new items to the input
	$('.acfb-input', self).result(function (e, data, formatted) {
		
		if (data.id == '') {
			// 'this' is the input control.  Here we assign the data values to default to the user input.
			data.email = $(this).attr('value');
			data.fullname = $(this).attr('value');
			data.contact_id = 0;
		}
		
		
		//Setup the HTML to add
		var HTML = ___autocompleteFBHTML___
		           .replace(/\{INPUT_NAME\}/g, settings.inputName )
		           .replace(/\{EMAIL\}/g, data.email )
				   .replace(/\{CONTACT_ID\}/g, data.contact_id )
				   .replace(/\{INDEX\}/g, $(this).parent().children('li.acfb-data').length )  // restrict counting of list items to this form control.
		           .replace(/\{LABEL\}/g, data.fullname);
		
		//add HTML to the list
		var inpt = $('.acfb-input', self).before(HTML);
		
		//add click event to the 'x'
		$('img',inpt.prev()).click(function (){
			removeData(this);
		});
		
		//clear and focus the input
		$('.acfb-input', self).val('').focus();
	});
	
	//Removes an item from the input
	function removeData (o) {
		$(o).unbind('click').parent().remove();
		$('.acfb-input', self).focus();
	};
	
	return this;
}

var ___autocompleteFBHTML___ = 
	'<li class="acfb-data">'+
		'<input type="hidden" name="{INPUT_NAME}[{INDEX}][email]" value="{EMAIL}" />'+
		'<input type="hidden" name="{INPUT_NAME}[{INDEX}][contact_id]" value="{CONTACT_ID}" />'+
		'<span>{LABEL}</span>'+
		'<img src="/img/delete.gif" />'+
	'</li>';
	
