/*
	UTILITY FUNCTION:
	This function return the y-coordinate offset of the top of the 
	visible part of the window.
*/

function getScrollXY() {
	var scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return [ scrOfY ];
}

/*
	THE SLIDER
	The slider is selected with any css selector that's suppored by jQuery. 
	When the user scrolls the window the selected element will animate so that it
	has the same distance from the top of the screen as before the animation.
*/


/*
This controller object keeps track of the slider.
*/
	
var scrollController = {
	cssSelector : "#sidebarBasket",
	top : 145        
};

/*
The function that slides the element.
*/
function placeIt(animate) {
    var animationDuration = 400;
	
	theElement = jQuery(scrollController.cssSelector);
	theElement.stop();
	var windowOffset = getScrollXY();
	      	
	/* 
	makes sure that it only scrolls the sidebar if it was about
	to exit the screen 
	*/
	if (windowOffset > scrollController.top) {
		
		// the maxium offset the element is allowed to have
		var index = jQuery(".restaurantTable").size();
		var theTable = jQuery(".restaurantTable").eq(index - 1);
		var maxOffset = theTable.height() + theTable.offset().top - theElement.height();
	
		if (windowOffset > maxOffset) {
		    theElement.animate({ top: maxOffset - scrollController.top }, animationDuration);
		    //theElement.css({ top: maxOffset - scrollController.top });
		} else {
		    theElement.animate({ top: windowOffset - scrollController.top }, animationDuration);
		    //theElement.css({ top: maxOffset - scrollController.top });
	    }	
	} else {
	    theElement.animate({ top: 0 }, animationDuration);
	    //theElement.css({ top: 0 });
	} 
}; 

/*
Event listener to to the scroll event. 
*/
jQuery(window).scroll(function () { 
	placeIt();
});

function registerScrollOnScroll() {
    jQuery(window).scroll(function() {
        placeIt();
    });
}
    	
