// Some JS to scroll through the featured posts

var featuredPosts = (function($) {

    // Members
    var m_currentIndex = 10; // a big number so it rolls over to the first one on the first call to next()
    var m_timeout = null;

    var prv_goto = function(index){
        var children = $('#featuredPostsList li');
        $(children[m_currentIndex]).removeClass('highlight');
        $('#featuredPostsNav-' + m_currentIndex).removeClass('highlight');
        
        var next = $(children[index]);
        $('#featuredPostsVisibleImage').html(next.find('.featuredPostsImage').clone().show());
        $(children).removeClass('highlight');
        next.addClass('highlight');
        $('#featuredPostsNav-' + index).addClass('highlight');        
        m_currentIndex = index;
    };
    
    // Public interface
    return {

        init: function(imagePrefix){
            // Build up the nav ui
            var nav = $('#featuredPostsNav');
            nav.append('<a href="" onclick="featuredPosts.previous(); return false;"><img src="' + imagePrefix + '/button_prev.png"/></a>');
            nav.append('<a href="" onclick="featuredPosts.next(); return false;"><img src="' + imagePrefix + '/button_next.png"/></a>');

            // We also need to set the proper height for the visible image. Each li is 45
            var count =  $('#featuredPostsList li').length;
            var height = count * 45;
            $('#featuredPostsVisibleImage').css('height', height+'px');
            
            // Show the first one
            featuredPosts.goto(0);
        },

        goto: function(index) {
            if (m_timeout) clearTimeout(m_timeout);
            if (index >= 0 || index < $('#featuredPostsList li').size() - 1){
                prv_goto(index);
            }
            
            m_timeout = setTimeout(function() { featuredPosts.next(); }, 5000);                        
        },
        
        previous: function() {
            if (m_timeout) clearTimeout(m_timeout);            
            nextIndex = m_currentIndex - 1;
            if (nextIndex < 0){
                nextIndex = $('#featuredPostsList li').size() - 1;
            }

            prv_goto(nextIndex);
            m_timeout = setTimeout(function() { featuredPosts.next(); }, 5000);            
        },
        
        next: function() {
            if (m_timeout) clearTimeout(m_timeout);            
            nextIndex = m_currentIndex + 1;
            if (nextIndex > $('#featuredPostsList li').size() - 1){
                nextIndex = 0;
            }

            prv_goto(nextIndex);
            m_timeout = setTimeout(function() { featuredPosts.next(); }, 5000);
        }
    };

}(jQuery));

