function sortSelectOptions(a, b){
	var A = a.name.toLowerCase();
	var B = b.name.toLowerCase();
	if (A < B){
		return -1;
	}else if (A > B){
		return  1;
	}else{
		return 0;
	}
}

(function($) {
		  
	$.fn.multiselect_autocomplete = function(options) {
		
		// make sure we have an options object
		options = options || {};
		
		// setup our defaults
		var defaults = { 
			  minChars: 0
			, width: 310
			, matchContains: true
			, autoFill: false
			, formatItem: function(row, i, max) {
				return row.name;
			}
			, formatMatch: function(row, i, max) {
				return row.name;
			}
			, formatResult: function(row) {
				return row.name;
			}
		};
		
		options = $.extend(defaults, options);
		
		return this.each(function() {
		
			//stick each of it's options in to an items array of objects with name and value attributes 
			var input_id=$(this).attr('id')+'_autocomplete';
			var $this = $(this),
				data = [],
				$input = $('<input type="text" id="'+input_id+'"/>');
			
			$container=$this.parents(':first');
			$choices_container=$this.parents('.double_list:first').find('.choices');
			$choices_container.append('<label for="'+input_id+'" style="padding: 0;font-size:9px !important; font-weight: normal;">Chercher un client à ajouter: </label>');
			
			if (this.tagName.toLowerCase() != 'select') { return; }
			
			$this.parents('form').submit(function(){
				$this.children('option').each(function(){
					if ($(this).val() != '') {
						$(this).attr('selected',true);
					}
				});	
			});
				
			
			$this.children('option').each(function() {
		
				var $option = $(this);
				
				if ($option.val() != '' && !$option.is(':selected')) { //ignore empty value options

					data.push({
						  name: $option.html()
						, value:$option.val()
					});
					
					$option.remove();
				}
				
				$option.attr('selected',false);
			});
			
			// insert the input after the select
			$input.appendTo($choices_container/*.css('left',$this.width()+50)*/);
			
			// add it our data
			data.sort(sortSelectOptions);
			options.data = data;
		
			//make the input box into an autocomplete for the select items
			$input.autocomplete(data, options);
		
			//make the result handler set the selected item in the select list
			$input.result(function(event, selected_item, formatted) { 
				$option=$this.find('option[value=' + selected_item.value + ']')[0];
				
				if($option==undefined){
					$option=$('<option value="'+selected_item.value+'">'+selected_item.name+'</option>').appendTo($this);
				}/*else{
					$option=$($option);
				}
				
				$option.attr('selected', true).parent();*/
				
				for(i in data){
					if(data[i]['value']==selected_item.value /*&& options.data[i]['name']==selected_item.name*/){
						data.splice(i,1);
					}
				}
				data.sort(sortSelectOptions);
				options.data = data;
				$input.flushCache().setOptions( options );
				//$choices_container.css('left',$this.width()+50)
				$this.trigger('change');
				$input.val('');
			});

      $input.blur(function(){
          // autocomplete has removed blank options
          // ensure that if value is removed we select the blank option if available
          if(this.value == ""){
            $($this.find('option[value=]')[0]).attr('selected', true);
          }

          /*   failsafe to ensure text box always represents the value being used in the select
           *   there are edge cases where if you leave the field part way through the word, or clear the value when no blank option is available
           *   that force a mismatch between the 2 elements
           */
          /*if(this.value != $this[0].options[$this[0].selectedIndex].text){
            $input.val($this[0].options[$this[0].selectedIndex].text);
          } */ 
      });
      
      //insert the delete controller
			$('<a href="" title="Supprimer les éléments sélectionnés"><img src="/iloCorePlugin/images/icons/cross_16.png" /></a>')
				.click(function(){
					$this.find("option:selected").each(function(){
						data.push({
						  name: $(this).html()
						, value:$(this).val()
						});
						$(this).remove();
					});
					data.sort(sortSelectOptions);
					options.data = data;
					$input.flushCache().setOptions( options );
					//$choices_container.css('left',$this.width()+50)
					return false;
				})
				.insertAfter($this);
		
			//set the initial text value of the autocomplete input box to the text node of the selected item in the select control
			//$input.val($this[0].options[$this[0].selectedIndex].text);
		
			//normally, you'd hide the select list but we won't for this demo
			//$this.hide();
		});
	};		  
  
})(jQuery);

