/*******************************************************************************
*	Labels in boxes
*	Phillip Parr
*	http://wizpip.com
*	2010
*
*	Used to places labels inside boxes in an accessible way
*******************************************************************************/

(function($){
		  
	$.fn.extend({
				
		labelsInside: function() {
		
			return this.each(function() {

				var form = $(this);
				
				/* labels in input boxes */
				form.find('input[type="text"]').each(function() {
					var label = form.find('label[for="'+$(this).attr('id')+'"]');
					label.css({position: "absolute", left: "-9999px"});
					if($(this).val() == '') {
						$(this).val(label.text());
					}
				});
				
				form.find('input[type="text"]').focus(function() {
					var label = form.find('label[for="'+$(this).attr('id')+'"]');
					if($(this).val() == label.text()) {
						$(this).val('');
					}
				});
				
				form.find('input[type="text"]').blur(function() {
					if($(this).val() == '') {
						var label = form.find('label[for="'+$(this).attr('id')+'"]');
						$(this).val(label.text());
					}
				});
				
				$(this).submit(function() {
					form.find('input[type="text"], input[type="password"]').each(function() {
						var label = form.find('label[for="'+$(this).attr('id')+'"]');
						if($(this).val() == label.text()) {
							$(this).val('');
						}
					});
				});
			
				/* labels in password boxes */
				form.find('input[type="password"]').each(function() {
					var label = form.find('label[for="'+$(this).attr('id')+'"]');
					label.css({position: "absolute", left: "-9999px"});
					if($(this).val() == '') {
						$(this).hide();
						var newPassword = document.createElement("input");
						newPassword.setAttribute('type', 'text');
						newPassword.setAttribute('id', $(this).attr('id')+'_dyn');
						newPassword.setAttribute('class', 'password');
						newPassword.value = label.text();
						$(this).after(newPassword);
					}
				});
				
				form.find('input.password').focus(function() {
					var label = form.find('label[for="'+($(this).attr('id')).replace(/_dyn/, '')+'"]');
					if($(this).val() == label.text()) {
						$(this).hide();
						form.find('#'+label.attr('for')).show().focus();
					}
				});
				
				form.find('input[type="password"]').blur(function() {
					if($(this).val() == '') {
						$(this).hide();
						form.find('#'+$(this).attr('id')+'_dyn').show();
					}
				});

			});
		}
	});
})(jQuery);
