var tweets = [];
var tweetIndex = 0;
var running = false;
var nextTweetInterval;


var urlPattern = /(\b(http|https):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
var hasTagPattern = /\#([a-zA-Z0-9]+)/i;

function fetchData (){
    $.ajax ( {
        url: 'data/twitter.php?' + new Date().getTime(),
        context:document.body,
        success: delegate ( this, dataSuccess ),
        error: delegate ( this, dataFailed ),
        dataType:'json'
    } );
}

function dataSuccess ( pData )
{
    tweets = [];
    tweetIndex = 0;

    var t;
    for ( var i in pData.results )
    {
        t = pData.results [ i ].text.replace ( urlPattern, '<a href="$1" target="_blank">$1</a>' );
        t = pData.results [ i ].text.replace ( hasTagPattern, '#<a href="http://twitter.com/search?q=%23$1" target="_blank">$1</a>' );

        tweets.push ( $(
            '<li><p><strong>' + pData.results [ i ].from_user + ':&nbsp;</strong>' + t + '</p></li>'
        ) );
    }

    goTweets();
    setTimeout ( 'fetchData()', 60000 );
}

function dataFailed( pData ){

    setTimeout ( 'fetchData()', 5000 );
}

function goTweets()
{
    $('#twitter_content').empty();
    nextTweet();
    nextTweet();
    nextTweet();
    clearInterval ( nextTweetInterval )
    nextTweetInterval = setInterval ( nextTweet, 4000 );
}

function nextTweet()
{
    $('#twitter_content').prepend ( tweets [ tweetIndex ] );
    var totalHeight = 0;

    $('#twitter_content li').each( function (){
        totalHeight += $(this).height();
    } )

    while ( totalHeight > $('#twitter_content').height() - 20 )
    {
        totalHeight -= $('#twitter_content li:last').height();
        $('#twitter_content li').last().remove();
    }

    $('#twitter_content li').removeClass ( 'last' );
    $('#twitter_content li').last().addClass ( 'last' );

    $('#twitter_content li:first').hide().slideDown ( 400 );

    tweetIndex++;

    if ( tweetIndex > tweets.length - 1 )
        tweetIndex = 0;
}

$(document).ready ( function(){
    fetchData();
    photoCarrousel();
});


var photos = [];
var index = 0;
function photoCarrousel()
{
    photos = $('#photofeed img');
    photos.load( fitPicture );
    setInterval( nextPicture, 3000 );
    nextPicture();
}

function nextPicture()
{
    photos.hide();
    photos.eq( index ).fadeIn();
    index++;
    if ( index > photos.length - 1 )
        index = 0;
}

function fitPicture()
{
    if( $(this).width() > $(this).height() )
    {
        $(this).width( 240 );
    } else {
        $(this).height( 170 );
    }
}
