/**
 * Composant jQuery qui ajoute l'autocomplétion à une balise HTML Input propre au site restodor.com  
 *
 * jquery.restodor.recherche.js
 *
 * @package   Restodor
 * @version   1.0
 * @copyright 2010 ID Soft Ltd. Tous droits réservés.
 * @author    SAMYNADEN Oveeyen <oveeyen.samynaden@idsoft.mu>
 */

var lis;

(function($) {
	
	$.fn.restodorRecherche = function(emptyText, autoCompleteOptions) {
	
	    var autoCompleteOpts = $.extend({}, $.fn.restodorRecherche.autoCompleteDefaults, autoCompleteOptions);
	    
	    // L'adresse sur le serveur qui renvoi les suggestions
	    suggestionUrl = '/recherche/ajaxsuggest';
				 
		return this.each(function() {
	
			// Définition de la valeur initiale
			this.value = emptyText;
			
			$(this).blur(function(event) {
								
		        if(this.value == '')
		        {
		        	this.value = emptyText;
		        }
		        
			});
			
			$(this).focus(function(event) {
				
		        if(this.value == emptyText)
		        {
		            this.value = '';		            
		        }
		        
			});
			
			var $rechercheForm = $('#' + this.id + '_form');
			
			$rechercheForm.submit(function()
			{
				var $input = $('#' + this.id +' :input');				
				var searchString = $input.val();
				
				if (searchString == '')
				{
					return false;
				}
			});
			
			$(this).autocomplete(suggestionUrl, autoCompleteOpts);
			
		});
		 
	};
	
	// Options à utilisés par défaut si non-spécifiés
    $.fn.restodorRecherche.autoCompleteDefaults = {
		delay: 10,
		minChars: 2,
		matchSubset: 0,
		matchContains: 0,
		maxItemsToShow: 13,
		cacheLength: 10,
		onItemSelect: selectItem,
		onFindValue: findValue,
		formatItem: formatItem,
		resultsClass: 'ac_results',
		autoFill: false
    };
	
})(jQuery);

function selectItem(li)
{
	var url = findValue(li);
	
	if (url != null)
	{
		$(location).attr('href', url);
	}
}

function findValue(li)
{
	if (li == null)
	{
		return null;
	}

	// if coming from an AJAX call, let's use the id as the value
	if(!!li.extra)
	{
		var sValue = li.extra[0];
	}
	// otherwise, let's just display the value in the text box
	else
	{
		var sValue = li.selectValue;
	}

	return sValue;
}

function formatItem(row)
{
	//return row[0] + " (id: " + row[1] + ")";
	return row[0];
}			