var Magictabs = Class.create({
  initialize: function(element) {
        this.element = $(element);
        if (this.element) {
            this.menu = $A(this.element.getElementsByTagName('a'));
            var initialTab = this.getInitialTab();
            if (initialTab) {
                this.show(this.getInitialTab());
                this.menu.without(initialTab).each(this.hide.bind(this));
            }
            this.menu.each(this.setupTab.bind(this));
        }
    },
    setupTab: function(element) {
        Event.observe(element, 'click', this.activate.bindAsEventListener(this), false);
    },
    activate: function(ev) {
        var elm = Event.findElement(ev, "a");
        Event.stop(ev);
        this.show(elm);
        this.menu.without(elm).each(this.hide.bind(this));
    },
    hide: function(elm) {
        var tabId = this.tabId(elm);
        if (tabId) {
            $($(elm).parentNode).removeClassName('active');
            $(this.tabId(elm)).hide();
        }
    },
    show: function(elm) {
        var tabId = this.tabId(elm);
        if (tabId) {
            $($(elm).parentNode).addClassName('active');
            $(this.tabId(elm)).show();
        }
    },
    tabId: function(elm) {
        var match = elm.href.match(/#(\w.+)/);
        if (Object.isArray(match)) {
            return match[1];
        }
    },
    getInitialTab: function() {
        if(document.location.href.match(/#(\w.+)/)) {
            var loc = RegExp.$1;
            var element = this.menu.find(function(value) { 
                return value.href.match(/#(\w.+)/)[1] == loc; }
            );
            return element || this.menu.first();
        } else {
            return this.menu.first();
        }
    }
});
