﻿(function($) {
    $.fn.tabsswitch = function(panes, container) {

        var tabsLI = $(this);
        
        // set interval for auto-switching
        var tabSwitchIntervalID = setInterval(function() { $.autoSwitchTab(tabsLI, panes, container); }, 5000);

        // bind the click events
        $(this).bind('click', function(e) {
            e.preventDefault();
            // clear the interval when clicked
            clearInterval(tabSwitchIntervalID);
            return $.switchTab($(this), panes, container);
        });

        // set the first item to be seen
        $.switchTab(tabsLI.parents().find('li:nth-child(1)'), panes, container);

        return tabsLI;
    };

    $.autoSwitchTab = function(tabs, panes, container) {

        // get the ul as default container for the li used here
        var tabsUL = $(tabs).parents('ul');

        // get the next item
        var nextItem = $('li a.selected', tabsUL).parents('li').next('li');

        // if next item doesn't exist go to the start
        if (nextItem.length != 0) {
            $.switchTab(nextItem, panes, container);
        } else {
            $.switchTab($('li:nth-child(1)', tabsUL), panes, container);
        }
    }


    $.switchTab = function(tab, panes, container) {
        // tab = clicked or called li element

        // get clicked index
        var tabIndex = tab.prevAll().length + 1;

        // add tab hide class to all tabs
        $(panes).hide().addClass('tabhide');

        // show the nth-child panel
        $(panes + ':nth-child(' + tabIndex + ')').show().removeClass('tabHide');

        // change colour of line separator thing
        var aTab = $('a', tab);
        var containerClass = aTab.attr('href').replace('#', '');
        $(container).removeClass().addClass(containerClass);

        // remove selected class from all tabs
        $('a', $(container)).removeClass();

        // add selected class to the active tab
        aTab.addClass('selected');
    };

})(jQuery);
