/*
 *	Watermark plugin
 *	Version: 0.6
 *	jQuery 1.2.6
 *	 
 *	Author: Gonzalo Villar
 *
 *	TODO:
*		- Inherit all the watermarked element CSS
 * 
*/
(function($){

    function CreateDummyInput(jElement, options, tagName)
    {
        var watermarkText = (options.watermarkText) ? options.watermarkText : jElement.attr('title');
		var dummyType = (tagName == 'INPUT') ? '<input type="text">' : '<textarea>';
        var dummyInput = $(dummyType)
            .attr('id', jElement.attr('id') + '_watermark')
            .addClass(options.watermarkCssClass)
			.addClass('watermarkPluginCustomClass') //workaround to fix some caching? problem in FF3. Used in window.unload hook to remove watermarks from the DOM
            .val(watermarkText)
			.css({overflowY: jElement.css('overflow-y'), overflowX: jElement.css('overflow-x')});
			
		if (tagName == 'INPUT') {
			dummyInput.get(0).size = jElement.get(0).size;
		}
		else if (tagName == 'TEXTAREA') {
			dummyInput.get(0).rows = jElement.get(0).rows;
			dummyInput.get(0).cols = jElement.get(0).cols;
		}
        else if(jElement.height() > 0)
            dummyInput.css({height: jElement.outerHeight(), width: jElement.outerWidth()});

        dummyInput.hide();
        jElement.before(dummyInput);
		return dummyInput;
    }

    function MakeWatermark(element, options)
    {
        element.each(function(){			
            var thisEl = jQuery(this);
            var found = false;
            
            // If we already have a watermark, get rid of it.
            if (this.jquery_watermark) {
                jQuery(this.jquery_watermark).remove();
                found = true;
            }

            var dummyInput = CreateDummyInput(thisEl, options, thisEl.attr('tagName').toUpperCase());
            
            this.jquery_watermark = dummyInput;

            dummyInput.focus(function(e){
                $(this).hide();
                thisEl.show().focus();
            });
                
            if (!found) {
                thisEl.blur(function(e){
                    if(this.value == '')
                    {
                        $(this).hide();
                        this.jquery_watermark.show();
                    }
                });
            }

            thisEl.blur();

        });

        return element;
    }

    $.fn.watermark = function(options){ return MakeWatermark(this, options);}	

})(jQuery);