(function($){
    $.fn.tabs = function(options) {  
        var defaults = {
            persistent: true,
            cookieTitle: "tabCookie",
            startPosition: 0
        };
        
        var options = $.extend(defaults, options);  
        
        cookieTab = function(id, cookieTitle) {
            $.cookie(cookieTitle, id)
        }
        
        tabLoad = function(tab) {
            var currentTab = tab.parent().parent().find('.selected');
            $(currentTab.attr('href')).hide();
            currentTab.removeClass('selected');
            
            $(tab.attr('href')).show();
            tab.addClass('selected');
        }
        
        
        return this.each(function() {  
            var tabs = $(this);
            var startPosition = options.startPosition;
            var persistent = options.persistent;
            var cookieTitle = options.cookieTitle;
            
            // Verify position of default tab
            startPosition = (typeof startPosition == 'undefined') ? 0 : parseInt(startPosition, 10);
            
            // Hide all content except selected
            tabs.find('a').each(function()
            {
                if($(this).attr('class').indexOf('selected') == -1)
                {
                    $($(this).attr('href')).hide();
                }
            });
            
            if(persistent == true) {
                if($.cookie(cookieTitle)) {		
                    tabs.find('a#'+$.cookie(cookieTitle)).addClass('selected');
                } else {
                    // Add class to define currently selected tab
                    tabs.find('a:eq('+ startPosition +')').addClass('selected');
                }
            } else {
                // Add class to define currently selected tab
                tabs.find('a:eq('+ startPosition +')').addClass('selected');
            }		
                    
            // Attach tab load functionality
            tabs.find('a').bind('click', function(e)
            {
                // Only go to load tab content if href is a hash
                if($(this).attr('href').indexOf('#') === 0)
                {
                    e.preventDefault();
                    tabLoad($(this));
                    if(persistent) {
                        cookieTab($(this).attr("id"), cookieTitle);
                    }
                }
            });			
        }); 	
    };
})(jQuery);
