Having searched everywhere for a solution to this problem, and attempting to use a few plugins like jQuery Way-points, to no degree of success, I hope that someone here will be able to offer a solution to this.
As it is a bit complex to explain with just text I have created a diagram of the behavior.
See this link as the spam filter will not let me post and image yet:

All elements are of a variable height depending on the content.
-
Having a sidebar which is much shorter than the page content,
-
Once the bottom of the sidebar div enters the viewport,
-
It will stay fixed in that position while the rest of the content will continue to scroll as normal.
-
Until the sidebar reaches the footer where it will scroll upwards with the footer as normal.
This would also work in reverse as the user scrolls in the opposite direction to the top of the page.
Here is my solution. You can use this example and implement your own solution to your problem.
HTML:
CSS:
and finally Javascript: