$(function() {

	// sets easier variable for window and offset created by static navigation bar
	var $window	= $(window),
		navoffset = $(".navbar").height() + 10;
	
	// fires on scroll
	$window.scroll(function() {

		// itterates through each module div
		$(".module").each(function(){

			// creates variables for modules and labels(height, top, bottom)
			// sets where top of viewing pane is (window + offset), and where the bottom of moved label will be
			var $mod = $(this);
				
			//only scrolls if there is a div of class labelcol in the module div
			if ($mod.children(".labelcol").length) {
				modheight = $mod.height(),
				modtop = $mod.offset().top,
				modbott = modheight + modtop,
				$label = $mod.children(".labelcol"),
				labelheight = $label.height(),
				labeltop = $label.offset().top,
				labelbott = labeltop + labelheight,
				wintop = $window.scrollTop() + navoffset,
				newbott =  wintop + labelheight + 20;

		
				// checks if top of viewing pane is inside current module
				if ((wintop > modtop) && (wintop < modbott)){
					// checks that new label position wont flow out of module
					if (newbott < modbott){
						// moves the label if it is 'safe' to do so
						if((wintop - modtop) > 10){
							$label.stop().animate({
				               	marginTop: wintop - modtop
				            });
				        }
			        }else{
			        	// moves label to bottom of module if it would otherwise overflow
			        	$label.stop().animate({
			               	marginTop: modheight - labelheight - 25
			            },1);
			        }
				}else{
					// if the viewing pane is not in the current module, label is set to top of module
					$label.stop().animate({
		               	marginTop: 15
		            });
				}
			}	

		});
	});
});
