﻿$.fn.setSliderOverlay = function () {
    var scrollpane = $(this);
    var scrollcontent = scrollpane.find('.scroll-content-overlay');
    var difference = scrollcontent.height() - scrollpane.height();
    if (difference > 0) {
        var proportion = difference / scrollcontent.height();
        var handleHeight = Math.round((1 - proportion) * scrollpane.height());
        handleHeight -= handleHeight % 2;
        scrollpane.after('<\div class="slider-wrap"><\div class="slider-vertical"><\/div><\/div>');
        var sliderwrap = scrollpane.next();
        sliderwrap.height(scrollpane.height()).css({ 'left': scrollpane.width() + 17, 'margin-top': '15px' });
        sliderwrap.find('.slider-vertical').slider(
    {
        orientation: 'vertical',
        range: 'max',
        min: 0,
        max: 100,
        value: 100,
        slide: function (event, ui) {
            var topValue = -((100 - ui.value) * difference / 100);
            scrollcontent.css({ top: topValue });
        }
    });
        $(sliderwrap).find(".ui-slider-handle").css({ height: handleHeight, 'margin-bottom': -0.5 * handleHeight });
        var origSliderHeight = sliderwrap.find('.slider-vertical').height();
        var sliderHeight = origSliderHeight - handleHeight;
        var sliderMargin = (origSliderHeight - sliderHeight) * 0.5;
        $(sliderwrap).find(".ui-slider").css({ height: sliderHeight, 'margin-top': sliderMargin });
        $(sliderwrap).find(".ui-slider-range").css({ top: -sliderMargin });
    }

    function onMouseWheel(delta, event) {
        var speed = 10;
        var sliderVal = sliderwrap.find('.slider-vertical').slider("value");
        sliderVal += (delta * speed);
        sliderwrap.find('.slider-vertical').slider("value", sliderVal);
        var topValue = -((100 - sliderVal) * difference / 100);
        if (topValue > 0)
            topValue = 0;
        if (Math.abs(topValue) > difference)
            topValue = (-1) * difference;
        scrollcontent.css({ top: topValue });
        event.preventDefault();
    }
    scrollcontent.bind({
        mousewheel: function (event, delta) {
            onMouseWheel(delta, event);
        }
    });
    scrollpane.next().bind({
        mousewheel: function (event, delta) {
            onMouseWheel(delta, event);
        }
    });

}
