/**
 * JQuery Plugin to create a simple scrollpanel
 */
(function($) {

	var currentScrollHandle = null;
    var lastMouseY = -1;
    var id = 0;

    // Checks if the specified coordinates are inside the bounding box
    // of the provided element
    var areCoordinatesInside = function(x,y,element) {
        var top = $(element).offset().top;
        var left = $(element).offset().left;
        var width = $(element).width();
        var height = $(element).height();
        return x > left && x < (left + width) &&
               y > top && y < (top + height);
    };
	
    // Global document mousedown handler
    var onDocumentMouseDownHandler = function(e) {
    	$('._jsScrollHandle').each(function()  {
    		if (areCoordinatesInside(e.pageX,e.pageY,$(this))) {
    			currentScrollHandle = $(this);
    			currentScrollHandle.css('cursor','pointer');
            }
    	});
    };

    // Global document mousemove handler
    var onDocumentMouseMoveHandler = function(e) {
        if (currentScrollHandle != null) {
            if (lastMouseY != -1) {
              var scrollpanel = $(currentScrollHandle).closest('._jsScrollpanel');
              var viewport = $('._jsViewport',scrollpanel);
              var content = $('._jsScrollContent',scrollpanel);
              
              var moveOffset = e.pageY - lastMouseY;
              var lastTop = currentScrollHandle.position().top;
              var nextTop = lastTop + moveOffset;
              var viewportHeight = viewport.css('height').replace('px','');
              var sliderHeight = currentScrollHandle.height();
              var contentHeight = content.height();
              var isViewportAtBottom = lastTop + sliderHeight >= viewportHeight;
              var isViewportAtTop = lastTop <= 0;
              
              if (isViewportAtTop && nextTop < lastTop) { 
            	  // Prevent scrolling through the roof
            	  nextTop = 0;         
              }
              if (isViewportAtBottom && nextTop > lastTop) { 
            	  // Prevent scroling through the bottom
            	  nextTop = viewportHeight-currentScrollHandle.height();            	  
              }
              
              currentScrollHandle.css('top',nextTop+'px');
              
              var scrollingPosition = nextTop/(viewportHeight-sliderHeight);
              var contentTop = -1*((contentHeight-viewportHeight)*scrollingPosition); 
              
              $(content).css('top',contentTop + 'px');
              //$('#debug').html(scrollingPosition + "/" + (viewportHeight));
            }
            lastMouseY = e.pageY;
        }
    };    
    
    // Global document mouseup handler
    var onDocumentMouseUpHandler = function(e) {
        if (currentScrollHandle != null) {
            // Stop the scrolling on mouse release
        	currentScrollHandle.css('cursor','');
        	currentScrollHandle = null;
        }
    };	
	
	$.fn.scrollpanel = function(options) {
        var config = jQuery.extend({
            // Default options:
            'maxHeight': '100',
            'borderSize': 1,
            'minHandleHeight': 55
        }).extend(options);
        this.each(function() {
        var height = $(this).height();
        if (height <= config.maxHeight) {
        	$(this).closest('.fms-container').addClass('fms-container-no-scrollbar');
        	return false;
        }
        
        var scollbarHeight = config.maxHeight;
    	var contentHeight = $(this).height();
        var scrollhandleHeight = Math.floor(config.maxHeight/contentHeight * config.maxHeight);

        if (scrollhandleHeight < config.minHandleHeight) {
        	scrollhandleHeight = config.minHandleHeight;
        }
       
        var scrollHandleId = 'jshandle-'+(id++);
        var outerHeight = parseInt(config.maxHeight)+config.borderSize;
        var template = $('<div class="_jsScrollpanel" style="position: relative; height:'+outerHeight+'px;overflow:hidden;" ><div class="_jsViewport viewport" style="display:block; height:'+config.maxHeight+'px;float:left" ></div><div class="_jsScrollbar scrollbar" style="height:'+(config.maxHeight)+'px;float:right;position:relative;"><div class="_jsScrollHandle scrollhandle" id="'+scrollHandleId+'" style="position:relative;top:0;height:'+scrollhandleHeight+'px"><div class="top"></div><div class="bottom"></div></div></div></div>');
        $(this).children().first().addClass('_jsScrollContent').css('position','relative');
        $(this).wrapAll(template);
        
        $('.bottom',template).position({
        	my: "left bottom",
        	at: "left bottom",
        	of: '#'+scrollHandleId
        });
        
        $(document).mousemove(onDocumentMouseMoveHandler);
        $(document).mousedown(onDocumentMouseDownHandler);
        $(document).mouseup(onDocumentMouseUpHandler);        
        });
	};	
	
})(jQuery);
