// Hacemos que las labels de los controles de formulario pasen a 
// ser valores por defecto de los formularios
Event.observe(window, 'load', function() {

	inputs = $$('input.watermark');
	
	for (input in inputs)
	{
		if (inputs[input].id)
		{
			inputs[input].value = $$('label[for = '+inputs[input].id+']')[0].collectTextNodes();
			$$('label[for = '+inputs[input].id+']')[0].remove();
			inputs[input].addClassName('watermark_enabled');
			inputs[input].addClassName('watermark_text');
			
			inputs[input].observe('focus', unset_field);
			inputs[input].observe('blur', reset_field);
        }
	}
	
	$$('select.completer').each(create_textbox_autocompleter);
	
	

}
)


function create_textbox_autocompleter(select)
{
	var input = new Element('input', {'type': 'text', 'id': select.id+"_autocompleter_input", 'class': select.className, 'name': select.id});
	var input_hidden = new Element('input', {'type': 'hidden', 'id': select.id, 'name': select.name});
	var div = new Element('div', {'id': select.id+'_autocompleter_div'});
	
	select.replace(input_hidden);
	$('message_receiver').ancestors()[0].insert(input, 'bottom');
	$('message_receiver').ancestors()[0].insert(div, 'bottom');
	
	
	var values = new Array();
	var options = new Array();
	select.childElements().each(function(name, index){if ((name.value) != ''){ options[name.text] = name.value} });	
	select.childElements().each(function(name, index){if ((name.value) != ''){ values.push(name.text)} });
		
	new Autocompleter.Local(input.id, select.id+'_autocompleter_div', values, {'fullSearch': true});
	
	var request = { 'input': input, 'input_hidden': input_hidden, 'options': options};
	
	Event.observe(input, 'blur', save_option.bindAsEventListener(request)); 
}

function save_option(event)
{
	$(this.input_hidden.id).value = this.options[$(this.input.id).value];
}

/**
*
* Función para limpiar un input en cuanto se entra en él, siempre
* y cuando el valor por defecto no se haya estabelcido ya (significaría
* que el usuario ya introdujo un valor). 
* 
*/
function unset_field(event)
{	
	if (Event.element(event).readAttribute("default") == null)
	{
		Event.element(event).writeAttribute("default", Event.element(event).value);
		Event.element(event).value="";		
		Event.element(event).removeClassName('watermark_text');
	}
}

/**
*
* Función para volver a introducir el valor por defecto del input en cuanto 
* sale de él, siempre que no se haya introducido otro valor
* 
*/
function reset_field(event)
{	
	if (Event.element(event).value == "")
	{
		Event.element(event).value=Event.element(event).readAttribute("default");
		Event.element(event).writeAttribute("default", null);
		Event.element(event).addClassName('watermark_text');		
	}
}