/* Copyright 2009 Palm, Inc.  All rights reserved. */

// TinyList: the non-widget widget for simple tappable lists

TinyList = {};

TinyList.setupTapHandler = function(div, model, handler) {
	Mojo.Event.listen(div, Mojo.Event.tap, TinyList._handleListTap.curry(model, div, handler));
};

TinyList.renderData = function(div, attrs, items) {
	if (!items || items.length == 0) {
		div.update();
		return;
	}
	
	TinyList._processListItems(items);
	
	var list = Mojo.View.render({template: attrs.itemTemplate, collection: items});
	if (attrs.listTemplate) {
		list = Mojo.View.render({template: attrs.listTemplate, object: { listElements: list }});
	}
	
	div.update(list);
};

TinyList._processListItems = function(items) {
	if (!items || items.length == 0) return;
	
	if (items.length == 1) {
		// apply single
		items[0].rowClass = 'single';
	} else {
		// apply first and last
		items[0].rowClass = 'first';
		items[items.length - 1].rowClass = 'last';
	}
	
	for (var i = 0; i < items.length; i++) {
		items[i].listIndex = i;
	}
	
};

TinyList._handleListTap = function(model, listDiv, handler, e) {
	e.originalEvent = e;
	
	var index = TinyList._getIndexOfTap(e.target, listDiv);
	if (!index) {
		Mojo.Log.error("Couldn't find x-list-index target for list tap");
		return;
	}
	e.item = model.items[index];
	
	handler(e);
};

TinyList._getIndexOfTap = function(element, toplevel) {
	var index = element.getAttribute('x-list-index');
	while (index == null && element != toplevel) {
		element = element.up();
		index = element.getAttribute('x-list-index');
	}
	return index;
};
