var blocksize = 25;
$(document).ready(function(){
	$('li.flyout').hover(function(){
		var doc_height = $(document).height();
		var target = $(this).find('ul.flyout:first')
		target.css('display', 'block');
		
		var css_top = 0 - blocksize;
		target.css('top', css_top);
		
		var top = target.offset().top;
		var height = target.height();
		
		var window_size = window.innerHeight;
		var scroll_top = $(document).scrollTop();
		var window_height = scroll_top + window_size;
		var parent_top = $(this).offset().top;
		
		if (top + height > window_height) {
			var bar = height - blocksize;
			var foo = parent_top - top;
			
			while ((top + height > window_height) && (bar > foo)) {
				top = top - blocksize;
				css_top = css_top - blocksize;
				foo = parent_top - top;
			}
			
			target.css('top', css_top);
		}
		
		if(top + height > doc_height){
			while (top + height > doc_height) {
				top = top - blocksize;
				css_top = css_top - blocksize;
			}
			
			target.css('top', css_top);
		}
		
		//alert('top: '+ top + " height: " + height + " doc: " + doc_height);
		
	}, function(){
		$(this).find('ul.flyout:first').css('display', 'none');
	});
});

