$(document).ready(function(){
    
    var slides = $('#billboard > li');
    realBBSelectedTab = null;
    
    // Set default alignment of all slides.
    slides.each(function(index, element){
        $(element).css('left', ((index > 0 ? 630 : 0)+(38*index))+"px");
    });
    
    // Attach click behavior to each slide anchor.
    slides.find('> h2 a').click(function(evt){
        evt.preventDefault();
        var selected = $($(this).closest('li')[0]);
        
        // abort click trigger if already animating.
        if (selected.data('anim')) return;

        var x = parseInt(selected.css('left'));
        var i = slides.index(selected);
        var midpoint = 931/2; // <<-- full billboard width: 931
        var ascend = (x < midpoint);
        var search = true;

        // when ascending, skip first slide and just shift overlaid slides.
        if (ascend) i++;

        while (search && i >= 0 && i < slides.length) {
            var neighbor = $(slides[i]);
            x = parseInt(neighbor.css('left'));
 
            // if the slide is not already animating...
            if (!neighbor.data('anim')) {
                // if ascending and slide is on the left side
                // or if descending and slide is on the right side
                if ((ascend && x < midpoint) || (!ascend && x > midpoint)) {
                    var to = (ascend ? '+=' : '-=')+'630px';
                    neighbor.data('anim', true).animate({left:to}, 750, function(){
                        $(this).data('anim', false);
                    });
                } else {
                    // stop searching once elements at their maximum limit are found.
                    search = false;
                }
            }
            ascend ? i++ : i--;
        }
        
        // update tab selection.
        if (!!realBBSelectedTab) realBBSelectedTab.fadeIn(500);
        realBBSelectedTab = selected.find('> h2 a').fadeOut(500);
    });
    
    // open initial slide.
    $('#billboard').hide().css('visibility', 'visible').fadeIn(1000);
    $(slides[0]).find('> h2 a').click();
});
