﻿function ScrollPane(view, directions)
{
	this.directions						= (directions ? directions : ScrollPane.VERTICAL_SCROLL|ScrollPane.HORIZONTAL_SCROLL);
    this.isVerticalScrollBarVisible     = (directions & ScrollPane.VERTICAL_SCROLL) ? true : false;
    this.isHorizontalScrollBarVisible   = (directions & ScrollPane.HORIZONTAL_SCROLL) ? true : false;
    this.horizontalScrollBar            = ((this.directions & ScrollPane.HORIZONTAL_SCROLL) ? new ScrollBar(ScrollBar.HORIZONTAL, 0, 100) : null);
    this.verticalScrollBar              = ((this.directions & ScrollPane.VERTICAL_SCROLL) ? new ScrollBar(ScrollBar.VERTICAL, 0, 100) : null);
    this.viewPane                       = new Container();
    
    extend(this, Container);
    
    if(this.horizontalScrollBar)
    {
		this.add(this.horizontalScrollBar, BorderLayout.SOUTH);
	}
	
	if(this.verticalScrollBar)
	{
		this.add(this.verticalScrollBar, BorderLayout.EAST);
		this.verticalScrollBar.onValueChanged.addEventListener(function(source, value) {
			view.setLocation(view.getX(), (-view.getPreferredsize().height) * (value/100));
		});
	}
	
    this.add(this.viewPane, BorderLayout.CENTER);
    // this.setLayout(new BorderLayout());
    
    this.setView(view);
};

ScrollPane.prototype = new Container;

ScrollPane.VERTICAL_SCROLL = 0x01;
ScrollPane.HORIZONTAL_SCROLL = 0x02;

ScrollPane.prototype.setView = function ScrollPane_setView(view)
{
	var thisRef = this;
	
	if(this.view)
	{
		this.viewPane.remove(this.view);
	}
	
    this.add(view);
    view.onSizeChanged.addEventListener(getMethodPointer(this, function(widget, oldSize, newSize) {
		thisRef.invokeUpdate();
    }));
};

ScrollPane.prototype.update = function ScrollPane_update()
{
    var hScrollBarSize = (this.isHorizontalScrollBarVisible ? this.horizontalScrollBar.getPreferredSize() : {width:0, height:0});
    var vScrollBarSize = (this.isVerticalScrollBarVisible ? this.verticalScrollBar.getPreferredSize() : {width:0, height:0});

    if(this.isVerticalScrollBarVisible)
    {
        this.verticalScrollBar.setBounds(this.getWidth() - vScrollBarSize.width, 0, vScrollBarSize.width, this.getHeight() - hScrollBarSize.height);
    }
    
    if(this.isHorizontalScrollBarVisible)
    {
        this.horizontalScrollBar.setBounds(0, this.getHeight() - hScrollBarSize.height, this.getWidth() - vScrollBarSize.width, hScrollBarSize.height);
    }
    
    this.viewPane.setBounds(0, 0, Math.max(this.getWidth() - vScrollBarSize.width, 0), Math.max(this.getHeight() - hScrollBarSize.height, 0));
};

ScrollPane.prototype.toString = function()
{
	return "Widget/ScrollPane";
}
