/**
 * Special scrolling events
 * @source http://james.padolsey.com/javascript/special-scroll-events-for-jquery/
 */
(function(){
	var special=jQuery.event.special;
	var uid1='D'+(+new Date());
	var uid2='D'+(+new Date()+1);

	special.scrollstart={
		setup:function(){
			var timer;
			var handler=function(evt){
				var _self=this;
				var _args=arguments;
				if(timer){
					clearTimeout(timer);
				}else{
					evt.type='scrollstart';
					jQuery.event.handle.apply(_self,_args);
				}
				timer=setTimeout(function(){
					timer=null;
				},special.scrollstop.latency);
			};
			jQuery(this).bind('scroll',handler).data(uid1,handler);
		},
		teardown:function(){
			jQuery(this).unbind('scroll',jQuery(this).data(uid1));
		}
	};
	special.scrollstop={
		latency:300,
		setup:function(){
			var timer;
			var handler=function(evt){
				var _self=this;
				var _args=arguments;
				if(timer)clearTimeout(timer);
				timer=setTimeout(function(){
					timer=null;
					evt.type='scrollstop';
					jQuery.event.handle.apply(_self,_args);
				},special.scrollstop.latency);
			};
			jQuery(this).bind('scroll',handler).data(uid2,handler);
		},
		teardown:function(){
			jQuery(this).unbind('scroll',jQuery(this).data(uid2));
		}
	};
})();

$(document).ready(function(){
	$(document).bind('scrollstop',function(){
		var s={};
		s.$=$(window);
		s.top=s.$.scrollTop();
		s.height=s.$.height();
		var c={};
		c.$=$('div.cnt1');
		c.top=c.$.offset().top;
		c.height=c.$.height();
		var e={};
		var o=0;
		$.each(['div.main','div.side'],function(){
			e.$=$(this+'');
			e.top=e.$.offset().top;
			e.height=e.$.outerHeight();
			if(s.top+10<e.top){
				if(s.top+10<c.top)o=0;
				else if(s.top-c.top+10+e.height<c.height)o=s.top-c.top+10;
				else o=c.height-e.height;
				e.$.stop(true,false).animate({
					'margin-top':o
				});
			}else if(e.height+40<s.height){
				if(s.top-c.top+10+e.height<c.height)o=s.top-c.top+10;
				else o=c.height-e.height;
				e.$.stop(true,false).animate({
					'margin-top':o
				});
			}else if(e.top+e.height+10<s.top+s.height){
				if(s.top+s.height<c.top+c.height+10)o=s.top+s.height-10-e.height-c.top;
				else o=c.height-e.height;
				e.$.stop(true,false).animate({
					'margin-top':o
				});
			}
		});
	});
});
