/*jshint browser:true*/
/**
 * For each element fed into it stores the target referenced in its
 * "for" attribute. When clicked cycles through the tabs and hides
 * any that are not to be selected.
 *
 * Default selected tag is denoted by having the class "selected"
 *
 */
;(function($) {

    $.fn.tabify = function(callback) {
        var tabs = [] ;

        return this.each(function() {
            var ele      = $(this) ;
            var content  = $('#' + ele.attr('target')) ;
            var selected = ele.hasClass('selected') ;
            var callbackArguments = {'ul':ele, 'target':content};

            tabs.push([ele, content, selected]) ;

            ele.click(function(e) {
                // input tabs should respect default behavior, others shouldn't
                if (!ele.is('input')) {
                    e.preventDefault() ;
                }

                var target = $(this).closest('.tab, .subtab') ;
                $.each(tabs, function(idx, e) {

                    if (target[0] === e[0][0]) {
                        // mark as the selected node
                        e[2] = true ;
                        tabs[idx] = e ;

                        // update the dom
                        if (!e[0].hasClass('selected')) {
                            e[0].addClass('selected') ;
                            e[1].show() ;
                        }
                    } else {
                        // update selected node
                        e[2] = false ;
                        tabs[idx] = e ;

                        // update the dom
                        e[0].removeClass('selected') ;
                        e[1].hide() ;

                    }
                }) ;
                if(callback) {
                    callback(callbackArguments);
                }

            }) ;
            if (selected && callback) {
                callback(callbackArguments);
            }
        }) ;
    } ;

})(jQuery) ;
