$(document).ready(function(){ 

    // Get a ref to the update div, set minWidth to the text item 
    $('input[autoCompleteText]').each(function(){ 
         
        var updateDiv = '#'+$(this).attr('update'); 
        $(updateDiv).css('minWidth',$(this).width()); 
        var autoCompleteRequestItem = $(this).attr('autoCompleteRequestItem'); 
        // Add a function to key up 
        $(this).bind('keyup', function(event){ 
            // On escape key, hide the suggestions 
            if(event.keyCode==27) { 
                $(updateDiv).hide(); 
            }else if($(this).val().length>0) { 
                // If a request is in process, return 
                if ( $(this).data('autoCompleteBusy') ) { 
                    return; 
                } 
                // Don't send a request if we just did it 
                var lastVal = $(this).data('lastAutoComplete'); 
                if(lastVal!=$(this).val()) { 
                    // Set busy flag 
                    $(this).data('autoCompleteBusy',true); 
                    // Record the search term 
                    $(this).data('lastAutoComplete',$(this).val()); 
                    // Call the function and get a JSON object 
                    $.getJSON($(this).attr('autoCompleteUrl'), 
                        autoCompleteRequestItem+"="+$(this).val(), 
                        function(itemList) { 
                          if(itemList !== null) { 
                            populateAutoComplete(itemList,updateDiv); 
                          } else { 
                            $(updateDiv).hide(); 
                          } 
                        } 
                    ); 
                    // Remove busy flag 
                    $(this).data('autoCompleteBusy',false); 
                }else{ 
                    $(updateDiv).show(); 
                } 
            }else{ 
                $(updateDiv).hide(); 
            } 
        }); 
    }); 
     
    function populateAutoComplete(itemList,updateDiv) {   
        var tag = updateDiv.substring(1); 
        // Build a list of links from the terms, set href equal to the term 
        var options = '';
        var backup = [];
        $.each(itemList, function(index, datos) {
        	 
        	for (var value in datos)
        	{
        		var fields = datos[value];
	        	var label = '';
	        	var clave = '';
            	
	        	for (var field in fields)
	        	{
	        		if(field != 'value')
	        		{
	        			label+= fields[field]+" ";
	        		}	
	        		else
	        		{
	        			clave = fields[field];
	        		}
	        	}
	        	
	            backup[value] = fields;
        	}
        	  
            options += '<a autoCompleteItem='+tag+' href="'+value+'" >' +  label + '</a>'; 
        }); 
        // Show them or hide div if nothing to show 
        if(options!=''){ 
            $(updateDiv).html(options); 
            $(updateDiv).show(); 
        } else { 
            $(updateDiv).hide(); 
        }
        
        
        // Attach a function to click to transfer value to the text box 
        $('a[autoCompleteItem='+tag+']').click(function(){
        	
        	//AVERIGUAMOS EL VALOR DEL SELECCIONADO
        	var seleccionado = $(this).attr('href');
        	
        	//ASIGNANDO VALORES A INPUTS
        	//$('input[update='+tag+']').val( seleccionado );
        	$('input[update='+tag+']').val( backup[seleccionado]['value'] );
            $('input[update='+tag+']').focus(); 
            
            var fields = backup[seleccionado];
            for (var field in fields)
            {
            	if(field != 'value'  &&  $('#'+field))
        		{
        			$('#'+field).val( fields[field] );
        		}
            }
        	
            //OCULTANDO MENU DE OPCIONES
            $(updateDiv).hide();
            return false; 
        }); 
    } 
});
