/*
 * mywatermark.js
 * 
 * This is a simplified version of jquery.watermark.js
 * -- You'll need to have a watermark class in your css
 * 
 */
(function($) {

	$.extend($,{
		clearwatermarks : function() {
			$("[wmwrap='true']").find("input,textarea").watermark({remove:true});
		},
		addwatermarks : function() {
			$("[watermark]").each(function(num,el) {
				$(el).watermark($(el).attr("watermark"));
			});
		},
		watermark : function(o) {
			o.el = $(o.el);
			if(o.remove) {
				if(o.el.parent().attr("wmwrap") == 'true') {
					o.el.parent().replaceWith(o.el);
				}
			} else {
				
				var f = o.el.parent("form");
				
				if(o.el.parent().attr("wmwrap") != 'true') {
					o.el = o.el.wrap("<span wmwrap='true' style='position:relative;'/>");
					
					/*
					 * This section is a hack for password fields. I didn't want to 
					 * put a label with absolute position in, since it's not consistant 
					 * between browsers, so I just added a text field. The new field will
					 * act as a surrogate holder of the watermark text for the password field.
					 */
					if (o.el.attr("type") == "password") {
						var newname = "txt" + o.el.attr("name");
						$("<input type='text' name='"+newname+"' id='"+newname+"' />").insertAfter(o.el);
						
						var o2 = $("#"+newname);
						if (o.el.attr("size")) o2.attr("size",o.el.attr("size"));
						o2.addClass("watermarkOn");
						
						var pwdfocus = function() {
							o2.hide(); o.el.show().focus(); 
						}
						var pwdblur = function() {
							if (!o.el.val()) { 
								o.el.hide(); o2.show();
							}
						}
						
						o2.focus(pwdfocus);
						o.el.blur(pwdblur);
						if( ! o.el.val()) { o2.val(o.html); o2.show(); o.el.hide();}
						return o.el;
					}
					
					var focus = function() {
						if (o.el.is(".watermarkOn")) o.el.removeClass("watermarkOn").val("");
					};
					
					var blur = function() {
						if(!o.el.val()) {
							if (o.html) o.el.addClass("watermarkOn").val(o.html);
						} 
					};
					
					var click = function() {
						o.el.focus();
					};
					
					o.el.focus(focus).blur(blur);
					f.bind("submit",click);
					if( ! o.el.val()) { o.el.val(o.html); o.el.addClass("watermarkOn");} 
				}
			}
			return o.el;
		}
	});
	
	$.fn.watermark = function(o) {
		return this.each(function() {
			if(typeof(o) == "string") {
				try {o = eval("(" + o + ")");} catch(ex) {o = {html:o};}
			}
			o.el = this;
			return $.watermark(o);
		});
	};
})(jQuery);

$().ready(function(){
	$.addwatermarks();
});
