﻿$j(function() {

    //I'm the tab handler code wrapper
    $j('.idsm_tabs_container').each(function() {

        //trap the main containers in variables
        var $widget = $j(this),
            $tabs = $j('ul.idsm_tabs', this),
            $panels = $tabs.siblings('div.idsm_tabs_panel');

        //I change the active panel based on its id
        function changePanel(hash) {
            var $panel = $panels.filter(hash)
            $panel.addClass('idsm_tabs_panel_current')
                    .siblings()
                       .removeClass('idsm_tabs_panel_current')
                    .end();

            //alert($panel.html());
            $panel.find('a.idsm_tabs_accessibility_anchor:first').get(0).focus();
            //.bind('focus', function(e){alert(this);})
            //    .trigger('focus');
        }

        //I change the active tab
        function changeTab($tab) {
            $tab
                .addClass('current')
                .siblings()
                    .removeClass('current');
        }

        //I disable the click handler for the tab accessibility anchors
        $j('a.idsm_tabs_accessibility_anchor', this).click(function(e) {
            e.preventDefault();
            e.stopPropagation();
        });

        //I handle clicks on the tabs themselves
        $j('li a', $tabs).bind('click.tabs', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var hash = (this.hash || '#');
            if (!hash.substring(1).length)
                return false;

            var $this = $j(this),
                $tab = $this.parent();

            changeTab($tab);
            changePanel(hash);

        });

        //I handle clicks on the "list of tabs" accessibility links in the tab
        $j('.idsm_tabs_paging a.innerTabHook2', $widget).bind('click.tabs', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var hash = (this.hash || '#');
            if (!hash.substring(1).length)
                return false;

            $j(hash).trigger('focus');
        });

    });

}); 