﻿/**
 * jQuery Watermark Plugin
 * (c) 2010 J.B. van der Burgh
 */
(function($) {
    var watermarkedClass = 'watermarked';
    var markedItems = [];
    /**
    * Opts: 
    * {
    *   textAttribute: 'attributeName' (if specified the value is used as watermark text)
    *   text: 'watermark text' (if omitted the current value is used)
    * }
    */
    $.fn.watermark = function(opts) {
        opts = opts || {};
        this.each(function() {
            var txt, me = $(this);
            if (opts.textAttribute) {
                txt = me.attr(opts.textAttribute);
            } else {
                txt = opts.text || this.value;
            }
            if (this.value == '' || this.value == txt) {
                me.addClass(watermarkedClass);
                me.val('' + txt);
            }
            function fb(e) {
                if (e.type == 'focus') {
                    if (this.value == txt) {
                        this.value = '';
                        $(this).removeClass(watermarkedClass);
                    }
                } else if (e.type == 'blur') {
                    if (this.value == '') {
                        this.value = txt;
                        $(this).addClass(watermarkedClass);
                    }
                }
            }
            me.bind('focus', fb).bind('blur', fb);
            me = null;
            markedItems.push({ txt: txt, el: this });
        });
        $('form').submit(function() {
            $.each(markedItems, function() {
                if (this.el.value == this.txt) {
                    this.el.value = '';
                }
            });
        });
    };

})(jQuery);
