﻿$( function() {
   
    function activateUrls( text ) {
        return text.replace( /(http:\/\/[^ ]+)/gi, "<a href=\"$1\">$1</a>" );
    }

    var TwitterFeed = function( container ) {

        this.search = function( query, count ) {
            
            query.rpp = count;
            query.lang = "en";
            
            $.ajax( {

                url: "http://search.twitter.com/search.json",
                dataType: "jsonp",
                data: query,
                
                success: function( response ) {

                    var results = response.results || response;
                    
                    if( results.length < 1 ) {
                        container.replaceWith( $("<div>There is no news at this time.</div>").addClass("twitter") );
                        return;
                    }
    
                    container.empty();

                    $( results ).each( function() {
                        container.append( $("<li>").html( activateUrls(this.text) ) );
                        container.append( $("<p>").html( activateUrls(posted(this.created_at) +' from '+ this.from_user) ) );
                    } );
                
                },
                
                error: function() {
                    container.replaceWith( $("<div>Unable to fetch the news at this time.</div>").addClass("twitter") );
                }

            } );
        };
        
        this.search( {
            from: container.attr("username"),
            q: container.attr("keyword")
        }, container.attr("count") || 3 );

    };
    
    $("ol.twitter").each( function() { new TwitterFeed( $(this) ); } );
    
} );

function posted(t) {
    var now = new Date();
    var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
    if (diff < 60) { return 'Less than a minute ago'; }
    else if (diff < 120) { return 'About a minute ago'; }
    else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
    else if (diff < (5400)) { return 'About an hour ago'; }
    else if (diff < (86400)) { return 'About ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
    else if (diff < (172800)) { return '1 day ago'; } 
    else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
}