
var timeout;
var timeoutLength = 6000;

function InitTabs(tabSelector, contentSelector, play, playSelector, pauseSelector) {

    if (play != undefined) {

        timeout = window.setTimeout(function () { SetNextTimeout(contentSelector, tabSelector, timeoutLength); }, timeoutLength);
    }

    SetActiveNavItem(tabSelector, 0);

    jQuery(tabSelector).click(function () {

        if (play != undefined) {

            clearTimeout(timeout);
            play = false;
        }

        var index = jQuery(this).index();
        SetItem(contentSelector, tabSelector, index);

        return false;
    });

    if (playSelector != undefined) {

        jQuery(playSelector).click(function () {

            if (!play) {

                SetNextItem(contentSelector, tabSelector);
                timeout = window.setTimeout(function () { SetNextTimeout(contentSelector, tabSelector, timeoutLength); }, timeoutLength);
                play = true;
            }

            return false;
        });
    }

    if (pauseSelector != undefined) {

        jQuery(pauseSelector).click(function () {

            clearTimeout(timeout);
            play = false;

            return false;
        });
    }

    return false;
}

function SetItem(contentSelector, tabSelector, index) {

    if (!jQuery(contentSelector).is(':animated')) {

        var currentIndex = GetCurrentIndex(tabSelector);
        
        if (index != currentIndex) {

            SetActiveNavItem(tabSelector, index);

            var selectorData = contentSelector.split(',');
            for (var ii = 0; ii < selectorData.length; ii++) {

                var item = jQuery(selectorData[ii]).get(index);

                jQuery(selectorData[ii]).removeClass("on");
                jQuery(selectorData[ii]).hide();

                jQuery(item).fadeIn();
                jQuery(item).addClass("on");
            }
        }
    }
}

function SetActiveNavItem(tabSelector, index) {

    var currentNavItem = jQuery(tabSelector).get(index);
    jQuery(tabSelector).removeClass("on");
    jQuery(currentNavItem).addClass("on");
}

function SetNextItem(contentSelector, tabSelector) {

    var index = GetCurrentIndex(tabSelector);
    var nextIndex = GetNextIndex(tabSelector, index);
    SetItem(contentSelector, tabSelector, nextIndex);
}

function GetCurrentIndex(tabSelector) {

    var currentItem = jQuery(tabSelector + '.on')[0];
    return jQuery(currentItem).index(); ;
}

function GetNextIndex(selector, index) {

    if (jQuery(selector).size() > index + 1)
        return index + 1;
    else
        return 0;
}

function SetNextTimeout(contentSelector, tabSelector, timeoutLength) {

    SetNextItem(contentSelector, tabSelector);
    timeout = window.setTimeout(function () { SetNextTimeout(contentSelector, tabSelector, timeoutLength); }, timeoutLength);
}
