/*
     * Input field decoration
     */
    function InputDeco(input, defaultValue, hasDefaultValue) {
        this.input = $(input);
        this.form = null;
        this.defaultValue = defaultValue;
        this.dirty = !hasDefaultValue;
        this.init();
    }

    $.extend(InputDeco.prototype, {
        init: function () {
            var self = this;
            this.form = this.input.parent("form:first");
            this.input.focus(function () { self.onFocus(); });
            this.input.blur(function () { self.onBlur(); });
            this.input.change(function () { self.onChange(); });
            this.form.submit(function () { self.onSubmit(); });

            if (this.dirty) {
                this.makeChanged(false);
            }
            else {
                this.makeDefault();
            }
        },
        onFocus: function () {
            //this.input.focus();

            if (!this.dirty) {
                this.makeChanged(true);
            }
            else {
                this.input.select();
            }
        },
        onBlur: function () {
            var dirty = this.dirty && this.input.val() != '';
            if (!dirty) {
                this.makeDefault();
                this.dirty = false;
            }
        },
        onChange: function () {
            // NOTE: depends on blur event to be triggered after the change event
            this.dirty = true;
        },
        onSubmit: function () {
            if (!this.dirty) {
                this.makeChanged(true);
            }
            return true;
        },
        makeDefault: function () {
            this.input.val(this.defaultValue);
            this.input.addClass('default');
        },
        makeChanged: function (clear) {
            if (clear) {
                this.input.val('');
            }
            this.input.removeClass('default');
        }
    });

    $.fn.extend({
        inputDeco: function (defaultValue, hasDefaultValue) {
            // argh - jQuery.fn.data was added in 1.2.3, currently we are running 1.2.2, so falling back to DOM expando
            // TODO: upgrade to 1.2.6 or 1.3
            //this.data('AXRO.InputDeco', new InputDeco(this, defaultValue, hasDefaultValue));
            this.each(function () {
                this.axroInputDeco = new InputDeco(this, defaultValue, hasDefaultValue);
                return false;
            });
        }
    });
