var timers = {};
var newest_seen = 1;


function fetchMoreData()
{
    // Clear all pending timeouts
    for( tag in timers ){
        clearTimeout( timers[tag] );
    }
    
    var url = "/ajax_update.php?slug=" + slug + "&newest_seen=" + newest_seen;
    
    //alert( url );
    
    // Fetch some more data from the server
    $.get( url, function(response, status){
        if( status == "success" ){
            
            //alert( response );
            
            data = eval( "(" + response + ")" );
            
            // Start the clock ticking again
            spoolUp();
        }
    });
}


// Update the specified tag
function updateTag(tag)
{    
    var tweet = data['tweets'][tag].shift();        
    if(!tweet) {
        // No more tweets available, fetch some more
        fetchMoreData();
        return;
    }
         
    var clean_tag = tag.replace("#","_"); // Clean tag name for user in dom IDs
    var node = $("#tweet-content-" + clean_tag);
        
    if( tweet.twitter_id > newest_seen ) newest_seen = tweet.twitter_id;
    
    node.html( tweet.text );
    
    var anchor = $("#tweet-author-" + clean_tag);
    
    anchor.html( "@" + tweet.author );
    anchor.attr("href", "http://twitter.com/" + tweet.author);    

    // Randomly delay and then update this tag again
    var delay = (Math.random() * 3000) + 5000;    
    timers[tag] = setTimeout( function(){
        updateTag(tag);
    }, delay);
    
}

function spoolUp()
{
    $(data['hashtags']).each(function(i, tag){        
        updateTag(tag, true);
    });
}

$(document).ready(function(){
    spoolUp( data );	
});