// Config
var locked = false;
var timing = 3000;
var currentCand = 0;
var scrollAnim = setTimeout(scrollNext,0);

// Disable links when missing
$('div#lucia-2008 div#candidate a').click(function(){
    if($(this).attr('rel') == 'disabled'){
        alert('Kommer snart!');
        return false;
    }else{
        return true;
    }
});

// Navigates to correct candidate
$('div#lucia-2008 ul#candidates a').click(function(){

    // If animation active
    if(locked)return false;

    // Remove auto-scroll
    clearTimeout(scrollAnim);
    
    // Scroll to anchor
    scrollTo($(this).attr('href'));
    
    // Set active link
    $(this).parent().addClass('active');
    
    return false;

});


// Scrolls to specified anchor
function scrollTo(anchor){
    
    // Do not animate if animation active
    if(locked)return false
    lock();
    
    // Set active link
    $('div#lucia-2008 ul#candidates li').each(function(){
        $(this).removeClass('active');
    });        
        
    // Scroll/animate to correct anchor
    var divOffset = $('div#lucia-2008 div#candidate-container').offset().left;
    var pOffset = $('div#lucia-2008 div#candidate-container '+anchor).offset().left-$('div#lucia-2008 div#candidate').offset().left;
    
    // Animate if needed & release lock
    if(pOffset != 0){
        $('div#lucia-2008 div#candidate').animate({scrollLeft: '+=' + pOffset + 'px'}, 1000,unlock);
    }else{
        unlock();
    }
}

// Scrolls to next in line
function scrollNext(){
    
    // Set next in anchor
    currentCand = (currentCand != 10)?currentCand+1:1;
    scrollTo('#candidate-'+currentCand);
    $('div#lucia-2008 ul#candidates li:eq('+(currentCand-1)+')').addClass('active');
    scrollAnim = setTimeout(scrollNext,timing);
    
    return true;
}

// lock / unlock so animation cant be interrupted
function lock(){locked = true;}
function unlock(){locked = false;}

