// Initialize.
var timerArray = new Array();
var timerCount = 0;
var speed = 2000;
var pause = false;

function resetTimeouts() {
    timerArray = new Array();
    timerCount = 0;
}

function clearTimeouts() {
    for (var i = 0; i < timerArray.length; i++) {
        clearTimeout(timerArray[i]);
    }
    resetTimeouts();
}

function init_rotator() {
    clearTimeouts();
    if ($('#rotator li').length <= 0) {
        timerArray[timerCount++] = setTimeout(init_rotator, 500);
        return;
    }
    else {
        pause = false;
        rotate($('#rotator li:visible:first'));
        return;
    }
}


$(function() {
    // Add click listeners for controls.
    $('#rotator_controls a').click(function() {
        //clear timer
        clearTimeouts();
        //pausing rotation
        pause = true;

        var anchor = $(this);
        // Show target, hide other <li>.
        $($(anchor).attr('href')).show().siblings('li').hide();
        // Add class="current" and remove from all others.
        $(anchor).addClass('current').parent('li').siblings('li').find('a').removeClass('current'); ;
        // Nofollow.
        $(anchor).blur();

        timerArray[timerCount++] = setTimeout(function() {
            init_rotator();
        }, 10000);
        return;
    });
});

// Rotator function.
function rotate(element) {
    // Stop, if user has interacted.
    if (pause) {
        return;
    }
    // Either the next /first <li>.
    var $next_li = $(element).next('li').length ? $(element).next('li') : $('#rotator li:first');

    // Either next / first control link.
    var $next_a = $('#rotator_controls a.current').parent('li').next('li').length ? $('#rotator_controls a.current').parent('li').next('li').find('a') : $('#rotator_controls a:first');

    // Animate.
    $('#rotator_controls a.current').removeClass('current');
    $next_a.addClass('current');

    // Continue.
    function doIt() {
        rotate($next_li);
    }

    // Fade out <li>.
    $(element).fadeOut(speed);

    // Show next <li>.
    $($next_li).fadeIn(speed, function() {
    // Slight delay.
        timerArray[timerCount++] = setTimeout(doIt, speed);
    });
}
