// #require mootools.js

if (MooTools) {
	var TabSwitch = new Class({
		initialize: function () { // func: initialize

			this.switches = $$('a.' + 'tab-switch');

			this.idList = this.switches.map(function (v) {
				var idx = v.href.indexOf('#');
				return v.href.substr(idx + 1, 999);
			});
			var tabImages = {};
			this.switches.each(function (v, i) {
				var id = this.idList[i];
				var imgs = v.getElements('img').map(function (img) {
					var img_off = new Image;
					var img_on = new Image;
					var img_act = new Image;
					var matches = img.src.match(/^(.+?)(?:-on|-act)?(\.(gif|jpg|jpeg|xbm|png))$/);
					if (matches) {
						img_off.src = matches[1] + matches[2];
						img_on.src = matches[1] + "-on" + matches[2];
						img_act.src = matches[1] + "-act" + matches[2];
					} else {
						img_off = img_on = img_act = img;
					}
					var the_obj = {
						target: img,
						normal: img_off,
						img_on: img_on,
						img_act: img_act
					};
					return the_obj;
				}, this);
				tabImages[id] = imgs;

				v.addEvent('mouseenter', (function () {
					if (id == this.current)	return;
					tabImages[id].each(function (theObj) {
						theObj.target.src = theObj.img_on.src;
					});
				}).bind(this));

				v.addEvent('mouseleave', (function () {
					if (id == this.current)	return;
					tabImages[id].each(function (theObj) {
						theObj.target.src = theObj.normal.src;
					});
				}).bind(this));

				v.addEvent('click', (function(event) {
					event = new Event(event).stop();
					this.switchContent(id);
				}).bind(this));

			}, this);

			this.tabImages = tabImages;

			var tabContents = {};

			this.idList.each(function (i) {
				tabContents[i] = $(i);
			});
			this.tabContents = tabContents;

			// initialize
			this.current = '';
			this.switchContent(this.idList[0]);
		},

		switchTab: function (id) { // func: switchTab
			if (!$defined(id) || !this.tabImages[id])	return;
			this.idList.each(function (o_id) {
				if (o_id != id) {
					this.tabImages[o_id].each(function (theObj) {
						theObj.target.src = theObj.normal.src;
					});
				}
			}, this);
			this.tabImages[id].each(function (theObj) {
				theObj.target.src = theObj.img_act.src;
			});
		},
		switchContent: function (id) { // func: switchContent
			if (!$defined(id) || !this.tabContents[id])	return;

			if (id == this.current)	return;
			this.current = id;
			this.switchTab(id);
			(function() {
				this.idList.each(function (o_id) {
					if (o_id != id) {
						this.tabContents[o_id].setStyle('display', 'none');
					}
				}, this);
				this.tabContents[id].setStyle('display', 'block');
			}).call(this);
		}
	});

	window.addEvent('domready', function(){
		var tabSwitch = new TabSwitch();
	});
}

