var Menu={
	init: function () {
		$$('#tabmenu img').each(function (i) {
			i.fader=new ButtonFader(i);
			Event.observe(i.parentNode, 'mouseover', i.fader.fadeOn.bindAsEventListener(i.fader));
			Event.observe(i.parentNode, 'mouseout', i.fader.fadeOff.bindAsEventListener(i.fader));
		});

		var logo = $('logo').select('img')[0];
		logo.fader = new ButtonFader(logo);
		Event.observe(logo.parentNode, 'mouseover', logo.fader.fadeOn.bindAsEventListener(logo.fader));
		Event.observe(logo.parentNode, 'mouseout', logo.fader.fadeOff.bindAsEventListener(logo.fader));
	}
};

var PI=3.1415926536;

function ButtonFader(baseimg) {

	this.baseimg=baseimg;
	this.targetopacity=0;
	this.srcopacity=0;
	this.currentopacity=0;
	this.num_frames=10;
	this.on_img=null;

	this.fadeOn = function () {
		this.fadeTo(1);
	};

	this.fadeOff = function () {
		this.fadeTo(0);
	};

	this.fadeTo = function (target) {
		this.srcopacity=this.currentopacity;
		this.targetopacity=target;
		this.play();
	}

	this.nextFrame = function () {		
		//var frac=0.5+0.5*Math.cos(this.frame*2*this.num_frames/PI);
		var frac=1-(++this.frame)/(1.0*this.num_frames);
		var opacity=frac*this.srcopacity+(1-frac)*this.targetopacity;
		
		if (opacity > 0.99)
			opacity=1;
		else if (opacity < 0.01)
			opacity=0;

		this.setOpacity(opacity);

		if (this.frame == this.num_frames || Math.abs(opacity - this.targetopacity) < 0.01)
			this.stop();
	};

	this.createOnImage = function () {
		var i=$(document.createElement('img'));
		i.src=this.baseimg.src.replace(/-off/, '-on');
		var offset=this.baseimg.positionedOffset();
		i.setStyle({
			position: 'absolute',
			top: offset.top+'px', 
			left: offset.left+'px',
			opacity: 0
		});
		this.on_img=i;
		this.baseimg.parentNode.appendChild(i);
	};

	this.setOpacity = function (opacity) {
		if (opacity == 0 && this.on_img) {
			this.on_img.remove();
			this.on_img = null;
			return;
		}
		if (!this.on_img)
			this.createOnImage();

		this.on_img.setStyle({'opacity':opacity});

		this.currentopacity=opacity;
	}

	this.play = function () {
		this.frame=0;

		if (this.timer) return;

		this.timer=setInterval(this.nextFrame.bind(this), 30);	
	};

	this.stop = function () {
		if (!this.timer) return;

		clearInterval(this.timer);
		this.timer=null
	};
}

Event.observe(document, 'dom:loaded', Menu.init);

// A function for bookmarking this site in Internet Explorer
function addToFavorites() {
	if (window.sidebar) {
        	window.sidebar.addPanel(document.title, location.href, "");
        }
	else if (window.external) {
		window.external.AddFavorite(location.href, document.title);
	}
}
