/*
 *	Watermark - add watermark to input element
 *  Phil Higgs - Oct 2008
*/
(function(jQuery){

    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('WPCC') 
            .val(watermarkText)
			.css({overflowY: jElement.css('overflow-y'), overflowX: jElement.css('overflow-x')});

        // Set width/height from element being replaced
        if(jElement.height() > 0)
//            dummyInput.css({height: jElement.outerHeight(), width: jElement.outerWidth()});
            dummyInput.css({height: jElement.height(), width: jElement.width()});
        // Override width/height from passed options
        if (options.height != null)
            dummyInput.css({height: options.height});	
        if (options.width != null)
            dummyInput.css({width: options.width});	
            
        dummyInput.hide();
        jElement.before(dummyInput);
		return dummyInput;
    }

    function MakeWatermark(element, options)
    {
        element.each(function(){			
            var thisEl = jQuery(this);

            var dummyInput = CreateDummyInput(thisEl, options, thisEl.attr('tagName').toUpperCase());

            dummyInput.focus(function(e){
                jQuery(this).hide();
                thisEl.show().focus();
            });
            
            thisEl.bind("hidewatermark", function(e){
                dummyInput.hide();
                thisEl.show();
            });
            
            thisEl.bind("showwatermark", function(e){
                dummyInput.show();
                thisEl.hide();
            });
            
            thisEl.blur(function(e){
                if(this.value == '')
                {
                    jQuery(this).hide();
                    dummyInput.show();
                }
            });
            thisEl.blur();
            
        });
        return element;
    }

	jQuery(window).unload(function(){
		jQuery('.WPCC').remove();
	});

    jQuery.fn.watermark = function(options){ return MakeWatermark(this, options);}	

})(jQuery);
