//
// ============================ class Scrolly ============================
//
// A class that keeps state and provides interaction methods for a scrollable
// horizontal list of items.  More than 1 scrolly can be present on the page
// at once and each is identified by an ID.  Page should import
// common/scrolly.css file.  Find an example of a VM file using this
// to get the idea of the HTML structure needed.

function Scrolly(id, max_items)
{
	this._id = id;
	this._count = 0;
	this._index = 0;
	this._max_items = max_items;
}

// Scrolly.set_count
Scrolly.prototype.set_count = function(count)
{
	this._count = count;
	
	var num_items = Math.min(this._max_items, count);
	
	// Automatically resize the scrolly items so that they fill the width
	// of their parent DIV.  We subtract 2 to allow for a border (this 
	// could be improved by actually figuring out the inner width
	// of the parent DIV.
	for (var i = 0; i < this._count; i++)
	{
		var div = document.getElementById("scrolly" + this._id + "_" + i);
		var new_width = div.parentNode.offsetWidth / num_items - 2;
		div.style.width = new_width + "px";
	}		
}

// Scrolly.decrement
Scrolly.prototype.decrement = function(val)
{
	this._index = Math.max(0, this._index - val);
	this.update();
}

// Scrolly.increment
Scrolly.prototype.increment = function(val)
{
	this._index = Math.min(this._count - this._max_items, this._index + val);
	this.update();
}

// Scrolly.update
Scrolly.prototype.update = function()
{
	var scrolly_left = document.getElementById("scrolly" + this._id + "_left");
	
	if (this._index <= 0)
	{
		scrolly_left.style.visibility = "hidden";
	}
	else
	{
		scrolly_left.style.visibility = "visible";
	}

	var scrolly_right = document.getElementById("scrolly" + this._id + "_right");
	if (this._index + this._max_items >= this._count)
	{
		scrolly_right.style.visibility = "hidden";
	}
	else
	{
		scrolly_right.style.visibility = "visible";
	}

	for (var i = 0; i < this._count; i++)
	{
		var div = document.getElementById("scrolly" + this._id + "_" + i);
		
		if ((i < this._index) || (i >= this._index + this._max_items)) 
		{
			div.style.display = "none";
		}
		else
		{
			div.style.display = "block";
		} 
	}
}
