(function ($) {
    /*
     * Input field decoration
     */
    function InputDeco(input, defaultValue) {
        this.input = $(input);
        this.form = null;
        this.defaultValue = defaultValue ? defaultValue : this.input.attr('title');
        this.init();
    }

    $.extend(InputDeco.prototype, {
        init: function () {
            var self = this;
            this.form = this.input.parents("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.isDirty()) {
                this.makeChanged(false);
            }
            else {
                this.makeDefault();
            }
        },
        isDirty: function () {
            return this.defaultValue != this.input.val() && this.input.val() != '';
        },
        onFocus: function () {
            if (!this.isDirty()) {
                this.makeChanged(true);
            }
            else {
                this.input.select();
            }
        },
        onBlur: function () {
            var dirty = this.isDirty() && this.input.val() != '';
            if (!dirty) {
                this.makeDefault();
                this.dirty = false;
            }
            else {
                this.makeChanged(false);
            }
        },
        onChange: function () {
            this.onBlur();
        },
        onSubmit: function () {
            if (!this.isDirty()) {
                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({
        /**
         * @param [defaultValue]
         * @param [hasDefaultValue]
         */
        inputDeco: function (defaultValue, hasDefaultValue) {
            this.each(function () {
                $(this).data('XTC.InputDeco', new InputDeco(this, defaultValue, hasDefaultValue));
            });
        }
    });
})(jQuery);

