/**
 * @author Mike Branski <tk421@stagebloc.com>
 *
 * This should get cleaned up and turned into a plugin.
 */
$(function(){
	// Cache the form selector
	var theForm = $('form:first'),
		textFields = $(':text, :password, textarea', theForm);

	// Select all text and password input fields, relative to the signup form
	textFields.each(function(){
		// Store the current object in a variable
		var obj = $(this),
			// Select the input's label, store it in a variable, then hide the field
			label = obj.siblings('label').hide();

		// Store the text of the label belonging to the input element
		obj.data('label', label.html());

		// If our element is a text input, we want to treat it differently from password fields
		if(obj.is(':text') || obj.is('textarea')) {

			if(obj.is(':text')) {
				obj.bind({
					focus: function(){
						// If the element's value matches the default, clear the field on focus
						if(obj.val() == obj.data('label')){
							obj.val('');
						}
					},
					blur: function(){
					// If the input's empty, set its value to the label text
						if(obj.val() == ''){
							obj.val(obj.data('label'));
						}
					}
				});
			} else if(obj.is('textarea')) {
				obj.bind({
					focus: function(){
						// If the element's text matches the default, clear the textarea on focus
						if(obj.text() == obj.data('label')){
							obj.text('');
						}
					},
					blur: function(){
						// If the textarea's empty, set its text to the label text
						if(obj.text() == ''){
							obj.text(obj.data('label'));
						}
					}
				})
			}


			obj.trigger('blur'); // Faux init functionality
		} else if(obj.is(':password')) {
			// Build the mask element
			var mask = $('<input />', {
				"class": 'text',
				type: 'text',
				value: obj.data('label')
			});

			// Insert the mask after the password field and bind the focus event
			mask.insertAfter(obj).bind({
				focus: function(){
					// Hide the mask, show the real password field, and trigger its focus
					mask.hide();
					obj.show().trigger('focus');
				}
			});

			// Start with the real password field hidden and bind the blur event
			obj.hide().bind({
				blur: function(){
					// If the password field is blank, hide it on blur and show the mask
					if(obj.val() == ''){
						obj.hide();
						mask.show();
					}
				}
			});
		}
	});

	// If the element's value matches the default, clear the field on submit
	theForm.submit(function(){
		textFields.not(':password').each(function(){
			if($(this).val() == $(this).data('label')){
				$(this).val('');
			}
		});
	});
});