/*
*	Watermark plugin
*	Version: 0.6
*	jQuery 1.2.6
*	 
*	Author: Gonzalo Villar
*
*	TODO:
*		- Inherit all the watermarked element CSS
* 
*/
(function ($) {

    function CreateDummyInput(jElement, options) {
        var watermarkText = (options.watermarkText) ? options.watermarkText : jElement.attr('title');
        var dummyType = '<label>';
        var dummyInput = $(dummyType)
            .attr('id', jElement.attr('id') + '_watermark')
            .attr('for', jElement.attr('id'))
            .addClass(options.watermarkCssClass)
			.addClass('watermarkPluginCustomClass') //workaround to fix some caching? problem in FF3. Used in window.unload hook to remove watermarks from the DOM
            .text(watermarkText);

        dummyInput.hide();
        jElement.before(dummyInput);

        return dummyInput;
    }

    function MakeWatermark(element, options) {
        element.each(function () {
            var thisEl = jQuery(this);

            var dummyInput = CreateDummyInput(thisEl, options);

            thisEl.focus(function (e) {
                thisEl.addClass("watermark-focused");
                dummyInput.hide();
            });

            thisEl.change(function (e) {
                if (this.value != '') {
                    dummyInput.hide();
                }
            });

            thisEl.watch("value", function (propertyName, oldValue, newValue) {
                var focusedEl = $('input.watermark-focused');
                if (this.value != '') {
                    dummyInput.hide();
                }
                else if (focusedEl.length > 0 && focusedEl[0].id != thisEl[0].id) {
                    dummyInput.show();
                }
            });

            thisEl.blur(function (e) {
                if (this.value == '') {
                    dummyInput.show();
                }
                thisEl.removeClass("watermark-focused");
            });

            if (thisEl.val() == '') {
                dummyInput.show();
            }

            thisEl.blur();

        });

        return element;
    }

    $(window).unload(function () {
        $('.watermarkPluginCustomClass').remove();
    });

    $.fn.watermark = function (options) { return MakeWatermark(this, options); }

})(jQuery);
