var PromptingField = Behavior.create({

    initialize: function() {
        this.changed = false;
        this.onblur();
        this.element.writeAttribute('autocomplete', 'off');
        this.element.up('form').observe('click', this.handleFormSubmission.bindAsEventListener(this));
    },

    setPrompt: function() {
        this.element.value = '';
        this.element.addClassName('prompting');
        this.element.value = this.element.title;
        this.changed = false;
    },

    clearPrompt: function() {
        this.element.value = '';
        this.element.removeClassName('prompting');
    },

		defaultPromptEnabled: function() { 
			var whitespace_regex = /(#[^;]*;|\s)/;
			return (this.element.value.gsub(whitespace_regex, '') == this.element.title.gsub(whitespace_regex, ''));
		},

    onblur: function(event) {
        if (this.element.value.blank()) {
            this.setPrompt();
        }
    },

    onfocus: function(event) {
        if(this.defaultPromptEnabled()) {
            this.clearPrompt();
        }
    },

    handleFormSubmission: function(event) {
        var element = event.element();
        if (element.match('input[type=submit]') || element.match('button[type=submit]') || element.match('input[type=image]')) {
            if(this.defaultPromptEnabled()) {
							this.clearPrompt();
            }
        }
    },

    onkeyup: function(event) { this.changed = true; },
    onchange: function(event) { this.changed = true; }

});


Event.addBehavior({'input.prompting_field, textarea.prompting_field': PromptingField});
