/**
 * This file is copyright Four Point Two Software Ltd.
 *
 * mikey@fourpointtwo.co.nz
 */

function $E(selector)
{
	return document.getElement(selector);
}


/*** Menu ***
 *
 * TODO: Make this handle an arbitary level of menus.
 *
 */
var Menu = new Class({

	initialize: function()
	{
		$$('ul.nav a').each(this.setupEvents, this);
	},

	show: function() {

		this.hoverElement.setStyle('display', 'block');
		this.addClass('hover');
		var hoverBg = document.getElementById("hoverBackground");
		if(hoverBg) {
			hoverBg.style.display="block";
		}
	},

	hide: function() {
		this.hoverElement.setStyle('display', 'none');
		this.removeClass('hover');

		var hoverBg = document.getElementById("hoverBackground");
		if(hoverBg) {
			hoverBg.style.display="none";
		}
	},

	setupEvents: function (item)
	{
		item.hoverElement = document.getElement('#'+item.id+'_hover');

		if(!item.hoverElement) {
			return;
		}

		item.addEvent('mouseover', this.show.bindWithEvent(item));
		item.addEvent('mouseout', this.hide.bindWithEvent(item));

		item.hoverElement.addEvent('mouseover', this.show.bindWithEvent(item));
		item.hoverElement.addEvent('mouseout', this.hide.bindWithEvent(item));
	}
});



/*** Rollovers ***/

var Rollovers = new Class({
	initialize: function() {

		$$('.rolloverable').each(function(item) {
			item.addEvent('mouseout', this.setImage);
			item.addEvent('mouseover', this.setImage);

			// Preload the active image
			new Element('img', {'src': item.src.replace(/.png/, '-active.png')})
		}, this);
	},

	setImage: function(event) {
		if(event.type == 'mouseout' && event.target.src.match(/-active/)) {
			event.target.src = event.target.src.replace(/-active.png/, '.png');
		}
		if(event.type == 'mouseover' && !event.target.src.match(/-active/)) {
			event.target.src = event.target.src.replace(/.png/, '-active.png');
		}
	}

});

/*** Expandable ***/

var Expandable = new Class({
	initialize: function() {

		$$('.expander').each(function(item) {

			$(item.rel).removeClass('hide');
			$(item.rel).slide('hide');

			item.addEvent('click', this.expand.bindWithEvent(this));

		}, this);
	},

	expand: function(event) {

		$(event.target.rel).slide();
		event.stop();
	}

});

window.addEvent('domready', function(){new Expandable()});