function suggestorInitialize(form, source, target, url, defaultVal, action)
{

	form.bind("keypress", function(e) {
         if (e.keyCode == 13) {
             return false;
        }
     });
     
     source.attr('autocomplete', 'off');
     
     source.focus(function(){
     	if(source.val() == defaultVal)
     	{
     		source.val('');
     	}
     })
 
      source.blur(function(){
     	if(source.val() == '')
     	{
     		source.val(defaultVal);
     	}
   		target.html('');
     })
  
     
     source.keyup(function(e){
		onKeyUp(e, url+$(this).val(), $(this), target, action);
	})

}


function jsonSearch(url, targetElement)
{

	$.getJSON(url, function(answer){
		targetElement.html('');
		var text = '';
		for(var prop in answer)
		{
			targetElement.append($('<li rel="'+answer[prop].id+'" id="element-'+answer[prop].id+'" class="element-suggestion" rel="'+answer[prop].id+'">'+answer[prop].name+'</li>'));
		}
		targetElement.find('li.element-suggestion:first-child').addClass('element-selected');
		
	});
	
	
}

function onKeyUp(e, url, source, target, action)
{
	text = source.val();
	if(e.keyCode == 27)
	{		
		target.html('');
	}
	else if(e.keyCode == 13 && target.html()=='')
	{	
		
		if(text.length>0 && text.length != '')
		{
			addElement(
			);
		}
	}
	else if(e.keyCode == 13 && target.html()!='')
	{
		source.val('');
		addElement(
			action,
			source,
			target
		);
	}
	else if(e.keyCode == 38)
	{
		if(target.find('li.element-selected').prev('li').html()!=null)
		{
			target.find('li.element-selected').removeClass('element-selected').prev('li').addClass('element-selected');
		}
	}
	else if(e.keyCode == 40)
	{
		if(target.find('li.element-selected').next('li').html()!=null)
		{
			target.find('li.element-selected').removeClass('element-selected').next('li').addClass('element-selected');
		}
	}
	else if(e.keyCode == 27)
	{
		$target.html('');
	}
	else if(source.val() =='')
	{	
		target.html('');
	}
	else
	{
		jsonSearch(url, target);
	}
	
	if($('#'+source.attr('rel')).val()!=source.val())
	{
		$('#'+$('#'+source.attr('rel')).attr('name')+'-id').val(0);
		$('#'+source.attr('rel')).val(source.val());
	}
	
	return false;
}


function addElement(action, source, list)
{

	if(action == 'source')
	{
		selectedItem = list.find('li.element-selected');
		source.val(selectedItem.text());
		list.html('');
		source.parent().find('#'+source.attr('name')+'-id').val(selectedItem.attr('rel'))
	}
	else if(action == 'hidden')
	{

		selectedItem = list.find('li.element-selected');

		list.html('');
		source.parent().find('#'+$('#'+source.attr('rel')).attr('name')+'-id').val(selectedItem.attr('rel'));
		$('#'+source.attr('rel')).val(selectedItem.text());
		source.val(selectedItem.text());		
	}

}








