$(document).ready(function(){
  
  
    if( $('.post_share').length > 0 && !($.browser.msie && parseInt($.browser.version) < 7) ) {
	
	//need to find a way to make this code plugin-able not every theme will have 'entry' as parent html element
	//parentNode???? and calculate values instead of static ones
	var $postShare = $('.post_share');
	
	//descripY is the location of the post content
        var descripY = parseInt($postShare.parent().offset().top) - 20;
        
		
        var pullX = $postShare.css('margin-left');
        
        $(window).data('scrollBound', false);
        
        function positionShareScroll() {
		var distanceLeft = parseInt($postShare.parent().offset().left) - 120;
		var pulledOutside = $postShare.css('margin-left') == pullX;
		
            var scrollY = $(window).scrollTop();
            var fixedShare = $postShare.css('position') == 'fixed';
            if ( scrollY > descripY && !fixedShare && pulledOutside) {
                $postShare.stop().css({
                    position: 'fixed',
                    left: 0,
                    top: 20,
                    marginLeft: distanceLeft
                });
            } 
			
			else if ( scrollY > descripY && fixedShare){
				$postShare.stop().css({
					marginLeft: distanceLeft
				});
			}
			
			else if ( scrollY < descripY && fixedShare ) {
                $postShare.css({
                    position: 'relative',
                    left: 0,
                    top: 0,
                    marginLeft: pullX
                });
            }
        }
        
        
        $(window).resize(function(){
            var windowW = $(window).width();
            var pulledOutside = $postShare.css('margin-left') == pullX;
            if ( windowW >= 1020 ) {
                if ( !$(window).data('scrollBound') ) {
                    if ( !pulledOutside ) {
                        $postShare.animate({ marginLeft: pullX });
                    }
                    $(window)
                        .data('scrollBound', true)
                        .bind('scroll.positionShare', function(){
                            positionShareScroll()
                        })
                    ;
                    positionShareScroll();
                }
            } else {
                if ( pulledOutside || $(window).data('scrollBound') ) {
                    $postShare
                        .css({ position: 'relative', left: 0, top: 0 })
                        .animate({marginLeft: 0})
                    ;
                    $(window)
                        .data('scrollBound', false)
                        .unbind('scroll.positionShare')
                    ;
                }
            }
        });
        $(window).resize(function () { positionShareScroll();
    });
    }
    
$(window).scroll(function () { positionShareScroll();
    });

  });
 