/**
 * A small util to use labels floating over their input fields.
 * This file replaces the unsettling behavior of writing the label's text
 * directly into the input fields. Instead the labels are placed and hidden
 * over their respective input field.
 * 
 * For showing the label's hover effects you can style the div.label.hovered 
 * CSS class.
 */
var Overlabels = {
	
	classes: [".formfield.overlabel .value input[type='text']", 
	          ".formfield.overlabel .value input[type='password']", 
	          ".formfield.overlabel .value textarea", 
	          ".formfield.overlabel .value select"
	         ],
		
	init: function() {
		// find all form_fields that are text fields and have a label
		$(Overlabels.classes.join(", ")).each(function(index, item){
			// if the field has a value
			if ($(item).val() && $(item).val().replace(/^\s*|\s*$/gi, "").length > 0) {
				// hide it's label
				$(this).parent().parent().find(".label").hide();
			} else {
				$(this).parent().parent().find(".label").show();
			}
			
			// if everything had already been initialized, don't re-apply all the events... 
			if ($(item).parent().parent().find(".label").is(".applied")) {
				return true;
			}
						
			// on focus, hide the label too
			$(item).focus(function(event) {
				$(this).parent().parent().find(".label").hide();
			});
			// on blur, re-show it, if the field still has no value
			$(item).blur(function(event) {
				if (this.value.replace(/^\s*|\s*$/gi, "").length <= 0) {
					$(this).parent().parent().find(".label").show();
				}
			});
						
			// when hovering over the input field show a hover effect for the label
			$(item).hover(function(event) {
				if (this.nodeName.toUpperCase() == "SELECT") {
					$(this).parent().parent().find(".label").hide();
				} else {
					$(this).parent().parent().find(".label").addClass("hovered");
				}
			}, function(event) {
				if (this.nodeName.toUpperCase() == "SELECT") {
					if (this.value.replace(/^\s*|\s*$/gi, "").length <= 0) {
						$(this).parent().parent().find(".label").show();
					}
				} else {
					$(this).parent().parent().find(".label").removeClass("hovered");
				}
			});

			// for the label of the current input field
			$(item).parent().parent().find(".label").each(function(i, it) {
				$(it).addClass("applied");
				// make sure it vanishes, as soon as clicked
				$(it).click(function(event) {
					$(this).hide();
					item.focus();
				});
				
				// and apply the same hover effect here too
				$(it).hover(function(event) {
					if (item.nodeName.toUpperCase() == "SELECT") {
						$(this).hide();
					} else {
						$(this).addClass("hovered");
					}
				}, function(event) {
					if (item.nodeName.toUpperCase() == "SELECT") {
						if (item.value.replace(/^\s*|\s*$/gi, "").length <= 0) {
							$(this).show();
						}
					} else {
						$(this).removeClass("hovered");
					}
				});
			});
		});
	}
};

$(document).ready(function() {
	Overlabels.init();
});

