(function($) {
    $.fn.navigation = function(query, o) {
        var self = $(this);
        
        var panes = $(query);

        var options = $.extend({
            tabs: 'a',
            current: 'current',
            onClick: null, 
            tabBorderWidth: 0,
            initialIndex: 0,
            initialPanelId: null
        }, o);
        
        
        var stripHash = function(dirty) {
            return dirty.replace(/[^#]*#/, '');
        }

        var setInitialIndex = function(ids){
            if ( o.initialPanelId ) {
                $.each(ids, function(i){
                    var id = stripHash(this);
                    if ( id == o.initialPanelId ) {
                        options.initialIndex = i;
                    }
                });
            }
        };
        
        // IE is a bitch: http://stackoverflow.com/questions/1806032/flash-video-still-playing-on-div-that-is-removed-using-jquery-ie-bug
        var hideFlashObjectsInSubTree = function(where) {
            var players = $(where).find('object');
            players.each(function() {
                var player = self;
                var placeholder = $('<div class="transpond-object-placeholder">');
                player.after(placeholder);
                placeholder.data('stored-flash-object', player.remove().get(0));
            });
        };

        var showFlashObjectsInSubTree = function(where) {
            var placeholders = $(where).find('.transpond-object-placeholder');
            placeholders.each(function() {
                var placeholder = self;
                var player = placeholder.data('stored-flash-object');
                if (player) {
                    placeholder.before(player);
                }
                placeholder.remove();
            });
            
            // this trick is needed to force Flash re-render its content properly
            var players = $(where).find('object');
            players.hide();
            setTimeout(function() {
                players.show();
            }, 0);
            
            // TODO: IE8/WinXP: play button on lala player (ecard) stays pressed in "play" mode, but music is not playing, user has to click again...
            //                  no big deal, we wanted to get rid of annoying background sound in the first place 
            //                  this is a lala player bug I would guess, because pacman flash embed works well
        };

        var swapPanes = function(i, id) {
            //hideFlashObjectsInSubTree(panes); // hide existing flash players
            panes.hide();
            panes.eq(i).show();
            //showFlashObjectsInSubTree(panes.eq(i)); // show flash players in newly showed pane
            // lets fire a view event when users switch tabs
            // HACK: prevent pageView call every second time
            // it depends on observation that this function is bound 2 times and we need to process /track only every first invocation
            // I store counter in (pseudo)DOMElementNode.counter, because putting is on global level is not working (same mystery as in fo.fbml)
            var node = panes.eq(i).children(0);
            if (!node.counter) node.counter = 0;
            node.counter++;
            
            $('.emailcapture_wrapper').css('display','block');
            if (panes.eq(i).children("#"+id)[0].init) {
                panes.eq(i).children("#"+id)[0].init();
                panes.eq(i).children("#"+id)[0].init = null;
            } else if (panes.eq(i).children("#"+id)[0].activate) {
                panes.eq(i).children("#"+id)[0].activate();
            }
            
            if (typeof options.onClick == "function") {
                options.onClick(i);
            }
            
            // log it
            $.galog.tabId = id;
            $.galog.pageView("app", "view", "view");
        };
        self.swapPanes = swapPanes;
        
        if ( self.length == 0 ) {
            // init default pane
            var id = panes.eq(0).children('div').eq(0).attr('id');
            swapPanes(0, id);
        }

        self.each(function(){
            if ( $(this).hasClass('dropdown') ) {
                var items = $(this).find('option');

                var selectEvent = function(i) {
                    if (panes[i] && items[i]) {
                        items.eq(i).attr('selected', true);
                        var id = stripHash(items[i].value);
                        swapPanes(i, id);
                    }
                };
                $(this).change(function(){ selectEvent(this.selectedIndex) });

                var ids = $.map(items, function(i){ return i.value });
                setInitialIndex(ids);
                selectEvent(options.initialIndex);
            }
            else {
                if ( $(this).hasClass('tabs-facebook') ) {
                    $(this).css('overflow', 'visible');
                }

                var tabItems = $(this).find(options.tabs);

                var clickEvent = function(i) {
                    if (panes[i] && tabItems[i]) {
                        tabItems.removeClass(options.current);
                        tabItems.eq(i).addClass(options.current);
                        var id = stripHash(tabItems[i].href);
                        swapPanes(i, id);
                    }
                };

                var bindEvent = function(e,i) {
                    $(e).click(function(){
                        clickEvent(i);
                        return false;
                    })
                };

                // Tabs - adjust width to fit
                var tab = tabItems.eq(0);
                var tabWidth = $(this).width()/tabItems.length - (16 + options.tabBorderWidth * 2);
                if ( tab.width() > tabWidth ) {
                    $('li>a', this).width(tabWidth);
                }

                for (var i=0,len=tabItems.length;i<len;i++) {
                    bindEvent(tabItems.eq(i),i);
                }

                var ids = $.map(tabItems, function(i){ return i.href });
                setInitialIndex(ids);
                clickEvent(options.initialIndex);
            }
        });
        
        return self;
    };
})(jQuery);