var TabSwitcher = Class.create({
	initialize: function (id, options) {
		this.options = Object.extend({
			tabContentSelector: 'div.tab_content',
			triggerEvent: 'click',
			callback: function () { }
		}, options || {});

		this.tabswitcher = $(id);
		this.tabs = this.tabswitcher.select('li a');
		this.tabContentAreas = $$(this.options.tabContentSelector);

		this._len = this.tabs.size();

		// Error handling
		if (this.tabswitcher == null || this.tabs.length == 0 || this.tabContentAreas.length == 0) {
			return;
		}

		this.setDefault();
		this.registerEventHandlers();
	},
	registerEventHandlers: function () {
		var destinationTab;

		// Register trigger events (e.g. 'click')  on tabs
		this.tabs.each(function (a) {
			a.observe(this.options.triggerEvent, function (e) {
				e.stop();
				this.hideAll();
				destinationTab = a.href.split('#')[1];
				$(destinationTab).show().fire("tab:shown");
				a.up().addClassName('active');
				this.options.callback(destinationTab);
			} .bind(this));
		}, this);
	},
	hideAll: function () {
		this.tabContentAreas.invoke('hide');
		this.tabs.each(function (a) {
			a.up().removeClassName("active");
		});
	},
	setDefault: function () {
		this.hideAll();

		var contentAreaId = false;
		var urlHash = window.location.hash.replace('#','') || false;
		if (urlHash) {
			for (var i=0; i<this._len; i++) {
				if (this.tabContentAreas[i].id == urlHash) {
					contentAreaId = urlHash;
				}
			}
		}

		if (contentAreaId) {
			this.tabs.each(function (a) {
				var linkedContentAreaId = a.href.split('#')[1]
				if (linkedContentAreaId == contentAreaId) {
                    this.tabswitcher.scrollTo();
					$(linkedContentAreaId).show();
					a.up().addClassName("active");
				}
            }.bind(this));
		} else {
			this.tabContentAreas.first().show();
			this.tabs.first().up().addClassName("active");
		}
	}
});  				    
			    
// Sample instantiation:
//
// new TabSwitcher('physician_tab_switcher');
//
//	new TabSwitcher('swedish_pediatric_specialists_address_switcher', {
//					tabContentSelector: '#swedish_pediatric_specialists address.multiple',
//					triggerEvent: 'mouseover'
//	});
	
	
