/**
 * 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 ScrollPins = {
	classes: [".scrollpin .pin" ],
		
	init: function() {
		var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
		var isIE7 = /msie|MSIE 7/.test(navigator.appVersion);
		if(isIE6 || isIE7) return false;
	
		// find all form_fields that are text fields and have a label
		$(ScrollPins.classes.join(", ")).each(function(index, element){
			/* Fix width of fixed area explicit to current inherited width */
			element = $(element).width( $(element).width() ).removeClass("pin").addClass("pinned");
			
			var scrollArea = element.parents(".scrollpin:first");
			var scrollAreaParent = scrollArea.parent().css({position:"relative"});
			scrollArea.css({top:scrollArea.position().top+"px",left:scrollArea.position().left+"px",position:"absolute"});
			
			$(window).bind("scroll.scrollPin", function(e){
				
				if (element.outerHeight(true) + Math.round(scrollArea.position().top) >= scrollAreaParent.height()) {
					scrollArea.css({height:"auto",position:"static"});
					element.removeClass("pinned pinned-bottom pinned-top").addClass("unpinned");
					return true;
				} else if (scrollArea.outerHeight(true) + Math.round(scrollArea.position().top) != scrollAreaParent.innerHeight()) {
					scrollArea.height(scrollAreaParent.innerHeight() - Math.round(scrollArea.position().top) - scrollArea.outerHeight(true) + scrollArea.height());
					scrollArea.css({position:"absolute"});
					element.removeClass("unpinned").addClass("pinned");
				}
				
				if($(this).scrollTop() > (scrollArea.offset().top + scrollArea.outerHeight(true) - element.outerHeight(true)) )
					$(element).addClass("pinned-bottom").removeClass("pinned-top floating");
				else if ($(this).scrollTop() > scrollArea.offset().top)
					$(element).addClass("floating").removeClass("pinned-top pinned-bottom");
				else $(element).addClass("pinned-top ").removeClass("floating pinned-bottom");
				return true;				
			});
			$(window).bind("unload.scrollPin", function(e){
				element.removeClass("pinned pinned-bottom pinned-top").addClass("pin unpinned");				
			});

		});
	}
};

$(window).load(function() {
	ScrollPins.init();
});

