var Module = Class.create();

Module.WishList = Class.create(
{
	cache: $H(),

	initialize: function()
	{
	},

	parse: function()
	{
		if (this.dropdown = $('category'))
		{
			this.target = this.dropdown.next();
			this.gift = $('giftID');
			this.category = $('categoryID');
			this.title = $('title');
			this.text = $('abstract');
			this.dropdown.observe('change', this.fill.bind(this));

			this.init();
		}

		$$('.help').each(function(element) { new Tip(element, element.title, { hook: { tip: 'bottomLeft', mouse: true }, offset: { x: 6, y: -6 }}); element.removeAttribute('title'); });
	},

	init: function()
	{
		if (this.gift.value)
		{
			this.dropdown.value = this.dropdown.gifts.select(function(gift) { return gift.ID == this.gift.value; }, this).first().categoryID;
		}
		else
		{
			this.category.value && (this.dropdown.value = this.category.value);
		}

		this.fill();
	},

	fill: function(event)
	{
		var content = '';

		this.category.value = this.dropdown.value;

		if (this.cache.get(this.dropdown.value))
		{
			content = this.cache.get(this.dropdown.value);
		}
		else
		{
			content = new Element('table', { cellspacing: 0, cellpadding: 2 });

			this.dropdown.gifts.select(function(gift) { return gift.categoryID == this.dropdown.value; }, this).each(function(gift, index)
			{
				content.insert(this.build(gift, index));
			}, this);

			this.cache.set(this.dropdown.value, content);
		}

		this.target.update(content);

		this.target.scrollTop = $('radio' + this.gift.value).up().getHeight()*$('radio' + this.gift.value).index;
	},

	build: function(data, index)
	{
		var tr = new Element('tr', { 'class': index%2 ? 'even' : 'odd' });
		var td = new Element('td');
		var input = new Element('input', { type: 'radio', name: 'radio', 'class': 'radio', id: 'radio' + data.ID, checked: data.ID == this.gift.value });

		input.index = index;
		input.observe('click', this.check.bind(this, data));

		tr.insert(new Element('td').update(new Element('img', { src: data.image, width: '36px' })));
		tr.insert(new Element('td').update(new Element('label', { 'for': 'radio' + data.ID }).update(data.title)));
		tr.insert(new Element('td').update(input));

		return tr;
	},

	check: function(data)
	{
		this.gift.value = data.ID;
		this.title.value = data.title;
		this.text.value = data.text;
	}
});

var wishlist = new Module.WishList();
document.observe('dom:loaded', function() { wishlist.parse(); });