(function($) {
    $.fn.enableDraggable = function(options) {
        var defaults = {
            laneLeft: 0,
            laneOffsetLeft: 0
        };

        var opts = $.extend(defaults, options);

        var lane = this;
        var laneLeft = opts.laneLeft;
        var laneOffsetLeft = opts.laneOffsetLeft;

        var laneWidth = lane.width();
        var laneHeight = lane.height();
        var windowWidth = $(window).width();
        var viewportWidth = windowWidth - laneLeft;
        lane.css({left: -laneOffsetLeft});
        lane.draggable("destroy"); // necessary if layout is called more than once

        if (laneWidth > viewportWidth) {
            // contents bigger than window
            lane.css({cursor: "move"});
            lane.draggable({axis: "x", containment: [-laneWidth + windowWidth, 0, laneLeft, laneHeight]});

            $("#slider-wrap").show();
            $("#slider").slider();
            $("#slider").slider("value", 0);

            lane.bind("drag", function(event, ui) {
                var scrollRatio = -(ui.position.left + laneOffsetLeft) / (laneWidth - viewportWidth);
                $("#slider").slider("value", Math.round(scrollRatio * 100));
            });
            
            $("#slider").bind("slide", function(event, ui) {
                var percentage = ui.value / 100.0;
                var scrollWidth = $("#strech").width();

                lane.css("left", -laneOffsetLeft + ((-laneWidth + viewportWidth) * percentage));
            });
        } else {
            lane.css({cursor: "auto"});
            $("#slider-wrap").hide();
        }
    }
})(jQuery);

