/*
 * Custom Autocompleter jQuery plugin
 * @category jQuery plugin
 * @copyright (c) mpunkt
 * @author reinhard naegler
 */

(function($){
	$.fn.completer = function(options){

		var defaults = {
		    disabled:           false,
		    delay:              500,    // Zeitliche Verzögerung bevor gesendet wird
		    minLength:          2,      // Min. Zeichenlänge für Suche
			identifyBy:			'id',	// Gefundene Einträge anhand JSON Parameter identifizieren
			afterChange:		null,
			onSelect:           null
		};
		var options = $.extend(defaults, options);

		return this.each(function(){

			var self = this;
			var selectedItem = null;

			$(self).autocomplete({
				source: "ajax/ajax.complete_shop_search.php?id="+PUid+"&f="+$(self).attr('name'),
				disabled: options.disabled,
				delay: options.delay,
				minLength: options.minLength,
				select: function(ev, ui){
					selectedItem = ui.item;
					self.enter();
					//return false; // false, damit das Input nicht mehr automatisch gefüllt wird
				}
			});
			$(self).blur(function(){
			    if(selectedItem == null && options.identifyBy) $(this).val('');
			});
			this.enter = function(){
				if(selectedItem != null){
                    if(typeof options.onSelect == 'function'){
						options.onSelect(selectedItem);
						return;
					}
				    // selectedItem.label verwenden anstatt selectedItem.value,
					// weil in selectedItem.value HTML-Quelltext (zB. &amp;) enthalten kann
			        //$(self).val(selectedItem.label+(options.identifyBy && selectedItem[options.identifyBy] ? ' ['+selectedItem[options.identifyBy]+']' : ''));
			        $(self).val($('<div />').html(selectedItem.label).text());
					if(options.identifyBy && selectedItem[options.identifyBy]){
						$(self).attr('readonly',true);
						$(self).parent().append('<div style="position:relative; width:'+$(self).outerWidth()+'px;"><input type="hidden" name="" value="" /><img src="images/icon_remove.png" class="hand abs" alt="" style="top:-18px; right:3px;" /></div>');
						$(self).parent().find('input[type=hidden]').attr('name', $(self).attr('name')).val(selectedItem[options.identifyBy]);
						$(self).removeAttr('name');
						$(self).parent().find('img').click(function(){
							self.clear();
						});
					}
			    } else {
					self.clear();
				}
				if(typeof options.afterChange == 'function') options.afterChange();
			};
			this.clear = function(){
			    if(options.identifyBy && selectedItem[options.identifyBy]){
				    $(self)
						.attr('readonly',false)
						.val('')
						.focus()
						.attr('name', $(self).parent().find('input[type=hidden]').attr('name'));
				    $(self).parent().find('img').parent().remove();
			    }
			    selectedItem = null;
			    if(typeof options.afterChange == 'function') options.afterChange();
			};

			if(options.identifyBy){
				// Evtl. vorbelegen
				if($(self).attr('pre_id') !== undefined){
				    selectedItem = {
						value: $(self).val(),
						label: $(self).val()
					};
					selectedItem[options.identifyBy] = $(self).attr('pre_id');
					self.enter();
					$(self).removeAttr('pre_id');
				}
			}
		});
	};
})(jQuery);

