/**
 *  Inline Hints for forms
 *  
 */

Form.InlineHints = function(form, hints, color) {
    this.form = $(form);
	this.hints = {};
	this.color = color?color:'#808080';

    this.onFocus		= this.onFocus.bindAsEventListener(this);
    this.onBlur			= this.onBlur.bindAsEventListener(this);
    this.setInputs		= this.setInputs.bindAsEventListener(this);
    this.resetInputs	= this.resetInputs.bindAsEventListener(this)
	
	this.addHints(hints);
    Event.observe(this.form, 'reset', this.setInputs);
    Event.observe(this.form, 'submit', this.resetInputs);
};

Form.InlineHints.prototype = {
	addHints: function(hints) 
	{
		for (var name in hints) {
			this.hints[name] = hints[name];
			var i = this.form[name];
			Event.observe(i, 'focus', this.onFocus);
			Event.observe(i, 'blur', this.onBlur);
		}
		this.setInputs();
	},

	removeHints: function(names) 
	{
		for (var i = 0; i < names.length; i++) {
			delete(this.hints[names[i]]);
		}
	},

    onFocus: function(e) 
	{
		var i = Event.element(e);
		var hint = this.hints[i.name].replace(/[\r\n]/g, '');
		var value = i.value.replace(/[\r\n]/g, '');
		if (value == hint.substr(0, value.length)) {
			i.style.color = i.oldcolor;
			i.value	= '';
		}
    },
	
    onBlur: function(e)	
	{
		var i = Event.element(e);
		if (i.value	== '') {
			i.style.color =	this.color;
			i.value	= this.hints[i.name];
		}
    },
	
    setInputs: function() 
	{
		for (var name in this.hints) {
			var i = this.form[name];
			var hint = this.hints[i.name].replace(/[\r\n]/g, '');
			var value = i.value.replace(/[\r\n]/g, '');
			if (value == '' || value == hint.substr(0, value.length)) {
				i.oldcolor = i.style.color;
				i.style.color = this.color;
				i.value = this.hints[name];
			}
			else {
				i.style.color = i.oldcolor;
			}
		}
    },
	
    resetInputs: function() 
	{
		for (var name in this.hints) {
			var i = this.form[name];
			var hint = this.hints[i.name].replace(/[\r\n]/g, '');
			var value = i.value.replace(/[\r\n]/g, '');
			if (value == hint.substr(0, value.length)) {
				i.style.color = i.oldcolor;
				i.value = '';
			}
		}
    }
};
