
Site.Controllers.FieldHint = Class.create
(
    Site.Base,
    {
        initialize: function($super, form, field, hint, options)
        {
            $super();
           
            this.form = form;
            this.field = field;

            this.hint = hint;
        
            this.setOptions
            (
                options,
                {
                    hintClassName: 'hint',
                    clearOnFocus: true,
                    restoreOnBlur: false,
                    clearOnFormSubmit: true                
                }
            );
        
            this.addObservers("fieldOnBlur", "fieldOnFocus", "onFormSubmit");
            
            this.setFieldHint();
            
            addEvent(this.field, 'focus', this.observers.fieldOnFocus);                        

            //Event.observe(field, 'focus', this.observers.fieldOnFocus); 
                
            if (this.options.restoreOnBlur)
            {
                addEvent(this.field, 'blur', this.observers.fieldOnBlur);                        
            }
            
            if (this.options.clearOnFormSubmit && this.form)
            {
                addEvent(this.form, 'submit', this.observers.onFormSubmit);                        
            }            
        },
    
    
        onFormSubmit: function(event)
        {
            if (this.field.value == this.hint)
                this.field.value = '';
        },


        setFieldHint: function()
        {
            Element.removeClassName(this.field, this.options.hintClassName);
        
            if (this.field.value == '' || this.field.value == this.hint)
            {
                Element.addClassName(this.field, this.options.hintClassName);

                this.field.value = this.hint;
            }
        },
    
        clearFieldHint: function()
        {
            Element.removeClassName(this.field, this.options.hintClassName);

            if (this.field.value == this.hint)
                this.field.value = '';
        },
    
        fieldOnFocus: function(event)
        {
            this.clearFieldHint(Event.element(event));  
        },
    
        fieldOnBlur: function(event)
        {
            this.setFieldHint(Event.element(event));  
        },
        
        destroy: function()
        {
            removeEvent(this.field, 'focus', fieldOnFocus);

            if (this.options.restoreOnBlur)
            {
                removeEvent(this.field, 'blur', this.observers.fieldOnBlur);                        
            }
            
            if (this.options.clearOnFormSubmit && this.form)
            {
                removeEvent(this.form, 'submit', this.observers.onFormSubmit);                        
            }
        }
        
           
    }
);
