(function(jQuery) {
    function BindTabs(tabs, div_ids)
    {
            tabs.each(function(i, a) {
                if (a.href.match(/\#/)) {
                    jQuery(a).unbind('click.mtz_tabs').bind('click.mtz_tabs', function() {
                        jQuery('a.on').removeClass('on');
                        jQuery('a[href$="' + a.href.replace(/.*\#/, '#') + '"]').addClass('on')
                        jQuery('#' + div_ids.join(',#')).hide();
                        jQuery('#' + a.href.split('#')[1]).show().addClass('ui-tabs-panel');

                        return false;
                    })
                }
            });
    }
    
    jQuery.fn.mtz_tabs = function() {
        jQuery(this).append("<div style='clear:both'></div>");
        return this.each(function() {
            var tabs = jQuery(" a", this).not('.no_tab');
            var div_ids = [];
            tabs.each(function(i, a) { if (a.href.match(/\#/) && !jQuery(a).is(".external")) { div_ids.push(a.href.split('#')[1]); } });
            for (x in div_ids) {
                var d = div_ids[x];
                var i = x;
                
                var anchor = window.location.href.replace(/^.*\#/, '')
                if (jQuery(tabs.get(i)).is('.on') || anchor == d) {
                    jQuery(tabs).removeClass('on');
                    jQuery('#' + div_ids.join(',#')).hide();
                    jQuery('#' + jQuery(tabs.get(i)).get(0).href.split('#')[1]).show().addClass('ui-tabs-panel');
                    jQuery(tabs.get(i)).addClass('on');
                    BindTabs(tabs, div_ids);
                    return false;
                }
                if (i == 0) { jQuery('#' + d).show().addClass('ui-tabs-panel'); jQuery(tabs.get(i)).addClass('on'); }
                else { jQuery('#' + d).hide(); jQuery(tabs[i]).removeClass('on'); }
            }
            BindTabs(tabs, div_ids);
        })
    }
})(jQuery);