(function($) {
    $.fn.scroll = function() {
        this.each(function() {
            $(this).html('<div class="wrapper">' + $(this).html() + '</div>');
            var innerHeight = $(this).innerHeight();
            var contentHeight = $(this).find('.wrapper').height();

            if (innerHeight > contentHeight)
                return;

            $(this).prepend('<div class="scrollbar"></div><a class="handle"></a>');

            var handleHeight = innerHeight / contentHeight * innerHeight;
            var mouseY = 0;
            var minX = 0;
            var maxX = 0;
            var handle = $(this).find('.handle');

            $(this).addClass("scroll");
            $(this).css({position: 'relative', overflow: "hidden"});
            $(this).find('.scrollbar').css({height: innerHeight, width: 20, position: "absolute", right: 0, top: 0});
            $(this).find('.handle').css({height: handleHeight, width: 20, position: "absolute", top: "0px", right: "0px"});
            $(this).find('.wrapper').css({marginRight: '20px'});

            $(this).find('.handle').mouseenter(function(e) {
                mouseY = e.pageY;
                mouseX = e.pageX;
                minX = mouseX - 40;
                maxX = mouseX + 40;
            });

            $(document).mousemove(function(e) {
                if (minX == 0 && maxX == 0)
                    return;

                if (e.pageX < minX || e.pageX > maxX) {
                    minX = maxX = 0;
                    return;
                }
                    
                var scrollable = handle.parent();
                var content = scrollable.find('.wrapper');

                dy = e.pageY - mouseY;
                scrollPosition = parseInt(handle.css('marginTop'));
                scrollPosition = scrollPosition + dy; 
                if (scrollPosition < 0) {
                    scrollPosition = 0;
                }   
                maxScroll = innerHeight - handleHeight;
                if (scrollPosition > maxScroll) {
                    scrollPosition = maxScroll;
                }   

                relScroll = scrollPosition / maxScroll;
                contentScroll = -(contentHeight + 100 - scrollable.height()) * relScroll;

                handle.css('marginTop', scrollPosition + 'px');
                content.css('marginTop', contentScroll + 'px');
                mouseY = e.pageY;
            }); 
        });   

        return this;
    }

 })(jQuery);

